1 | n/a | import io |
---|
2 | n/a | import os |
---|
3 | n/a | |
---|
4 | n/a | from .context import reduction, set_spawning_popen |
---|
5 | n/a | from . import popen_fork |
---|
6 | n/a | from . import spawn |
---|
7 | n/a | from . import util |
---|
8 | n/a | |
---|
9 | n/a | __all__ = ['Popen'] |
---|
10 | n/a | |
---|
11 | n/a | |
---|
12 | n/a | # |
---|
13 | n/a | # Wrapper for an fd used while launching a process |
---|
14 | n/a | # |
---|
15 | n/a | |
---|
16 | n/a | class _DupFd(object): |
---|
17 | n/a | def __init__(self, fd): |
---|
18 | n/a | self.fd = fd |
---|
19 | n/a | def detach(self): |
---|
20 | n/a | return self.fd |
---|
21 | n/a | |
---|
22 | n/a | # |
---|
23 | n/a | # Start child process using a fresh interpreter |
---|
24 | n/a | # |
---|
25 | n/a | |
---|
26 | n/a | class Popen(popen_fork.Popen): |
---|
27 | n/a | method = 'spawn' |
---|
28 | n/a | DupFd = _DupFd |
---|
29 | n/a | |
---|
30 | n/a | def __init__(self, process_obj): |
---|
31 | n/a | self._fds = [] |
---|
32 | n/a | super().__init__(process_obj) |
---|
33 | n/a | |
---|
34 | n/a | def duplicate_for_child(self, fd): |
---|
35 | n/a | self._fds.append(fd) |
---|
36 | n/a | return fd |
---|
37 | n/a | |
---|
38 | n/a | def _launch(self, process_obj): |
---|
39 | n/a | from . import semaphore_tracker |
---|
40 | n/a | tracker_fd = semaphore_tracker.getfd() |
---|
41 | n/a | self._fds.append(tracker_fd) |
---|
42 | n/a | prep_data = spawn.get_preparation_data(process_obj._name) |
---|
43 | n/a | fp = io.BytesIO() |
---|
44 | n/a | set_spawning_popen(self) |
---|
45 | n/a | try: |
---|
46 | n/a | reduction.dump(prep_data, fp) |
---|
47 | n/a | reduction.dump(process_obj, fp) |
---|
48 | n/a | finally: |
---|
49 | n/a | set_spawning_popen(None) |
---|
50 | n/a | |
---|
51 | n/a | parent_r = child_w = child_r = parent_w = None |
---|
52 | n/a | try: |
---|
53 | n/a | parent_r, child_w = os.pipe() |
---|
54 | n/a | child_r, parent_w = os.pipe() |
---|
55 | n/a | cmd = spawn.get_command_line(tracker_fd=tracker_fd, |
---|
56 | n/a | pipe_handle=child_r) |
---|
57 | n/a | self._fds.extend([child_r, child_w]) |
---|
58 | n/a | self.pid = util.spawnv_passfds(spawn.get_executable(), |
---|
59 | n/a | cmd, self._fds) |
---|
60 | n/a | self.sentinel = parent_r |
---|
61 | n/a | with open(parent_w, 'wb', closefd=False) as f: |
---|
62 | n/a | f.write(fp.getbuffer()) |
---|
63 | n/a | finally: |
---|
64 | n/a | if parent_r is not None: |
---|
65 | n/a | util.Finalize(self, os.close, (parent_r,)) |
---|
66 | n/a | for fd in (child_r, child_w, parent_w): |
---|
67 | n/a | if fd is not None: |
---|
68 | n/a | os.close(fd) |
---|