1 | n/a | import os |
---|
2 | n/a | import sys |
---|
3 | n/a | import signal |
---|
4 | n/a | |
---|
5 | n/a | from . import util |
---|
6 | n/a | |
---|
7 | n/a | __all__ = ['Popen'] |
---|
8 | n/a | |
---|
9 | n/a | # |
---|
10 | n/a | # Start child process using fork |
---|
11 | n/a | # |
---|
12 | n/a | |
---|
13 | n/a | class Popen(object): |
---|
14 | n/a | method = 'fork' |
---|
15 | n/a | |
---|
16 | n/a | def __init__(self, process_obj): |
---|
17 | n/a | sys.stdout.flush() |
---|
18 | n/a | sys.stderr.flush() |
---|
19 | n/a | self.returncode = None |
---|
20 | n/a | self._launch(process_obj) |
---|
21 | n/a | |
---|
22 | n/a | def duplicate_for_child(self, fd): |
---|
23 | n/a | return fd |
---|
24 | n/a | |
---|
25 | n/a | def poll(self, flag=os.WNOHANG): |
---|
26 | n/a | if self.returncode is None: |
---|
27 | n/a | while True: |
---|
28 | n/a | try: |
---|
29 | n/a | pid, sts = os.waitpid(self.pid, flag) |
---|
30 | n/a | except OSError as e: |
---|
31 | n/a | # Child process not yet created. See #1731717 |
---|
32 | n/a | # e.errno == errno.ECHILD == 10 |
---|
33 | n/a | return None |
---|
34 | n/a | else: |
---|
35 | n/a | break |
---|
36 | n/a | if pid == self.pid: |
---|
37 | n/a | if os.WIFSIGNALED(sts): |
---|
38 | n/a | self.returncode = -os.WTERMSIG(sts) |
---|
39 | n/a | else: |
---|
40 | n/a | assert os.WIFEXITED(sts) |
---|
41 | n/a | self.returncode = os.WEXITSTATUS(sts) |
---|
42 | n/a | return self.returncode |
---|
43 | n/a | |
---|
44 | n/a | def wait(self, timeout=None): |
---|
45 | n/a | if self.returncode is None: |
---|
46 | n/a | if timeout is not None: |
---|
47 | n/a | from multiprocessing.connection import wait |
---|
48 | n/a | if not wait([self.sentinel], timeout): |
---|
49 | n/a | return None |
---|
50 | n/a | # This shouldn't block if wait() returned successfully. |
---|
51 | n/a | return self.poll(os.WNOHANG if timeout == 0.0 else 0) |
---|
52 | n/a | return self.returncode |
---|
53 | n/a | |
---|
54 | n/a | def terminate(self): |
---|
55 | n/a | if self.returncode is None: |
---|
56 | n/a | try: |
---|
57 | n/a | os.kill(self.pid, signal.SIGTERM) |
---|
58 | n/a | except ProcessLookupError: |
---|
59 | n/a | pass |
---|
60 | n/a | except OSError: |
---|
61 | n/a | if self.wait(timeout=0.1) is None: |
---|
62 | n/a | raise |
---|
63 | n/a | |
---|
64 | n/a | def _launch(self, process_obj): |
---|
65 | n/a | code = 1 |
---|
66 | n/a | parent_r, child_w = os.pipe() |
---|
67 | n/a | self.pid = os.fork() |
---|
68 | n/a | if self.pid == 0: |
---|
69 | n/a | try: |
---|
70 | n/a | os.close(parent_r) |
---|
71 | n/a | if 'random' in sys.modules: |
---|
72 | n/a | import random |
---|
73 | n/a | random.seed() |
---|
74 | n/a | code = process_obj._bootstrap() |
---|
75 | n/a | finally: |
---|
76 | n/a | os._exit(code) |
---|
77 | n/a | else: |
---|
78 | n/a | os.close(child_w) |
---|
79 | n/a | util.Finalize(self, os.close, (parent_r,)) |
---|
80 | n/a | self.sentinel = parent_r |
---|