Debian Codegraph @

Lib/multiprocessing/popen_fork.py

raw
1 import atexit
2 import os
3 import signal
4
5 from . import util
6
7 __all__ = ['Popen']
8
9 #
10 # Start child process using fork
11 #
12
13 class Popen(object):
14 method = 'fork'
15
16 def __init__(self, process_obj):
17 util._flush_std_streams()
18 self.returncode = None
19 self.finalizer = None
20 self._launch(process_obj)
21
22 def duplicate_for_child(self, fd):
23 return fd
24
25 def poll(self, flag=os.WNOHANG):
26 if self.returncode is None:
27 try:
28 pid, sts = os.waitpid(self.pid, flag)
29 except OSError:
30 # Child process not yet created. See #1731717
31 # e.errno == errno.ECHILD == 10
32 return None
33 if pid == self.pid:
34 self.returncode = os.waitstatus_to_exitcode(sts)
35 return self.returncode
36
37 def wait(self, timeout=None):
38 if self.returncode is None:
39 if timeout is not None:
40 from multiprocessing.connection import wait
41 if not wait([self.sentinel], timeout):
42 return None
43 # This shouldn't block if wait() returned successfully.
44 return self.poll(os.WNOHANG if timeout == 0.0 else 0)
45 return self.returncode
46
47 def _send_signal(self, sig):
48 if self.returncode is None:
49 try:
50 os.kill(self.pid, sig)
51 except ProcessLookupError:
52 pass
53 except OSError:
54 if self.wait(timeout=0.1) is None:
55 raise
56
57 def interrupt(self):
58 self._send_signal(signal.SIGINT)
59
60 def terminate(self):
61 self._send_signal(signal.SIGTERM)
62
63 def kill(self):
64 self._send_signal(signal.SIGKILL)
65
66 def _launch(self, process_obj):
67 code = 1
68 parent_r, child_w = os.pipe()
69 child_r, parent_w = os.pipe()
70 # gh-146313: Tell the resource tracker's at-fork handler to keep
71 # the inherited pipe fd so this child reuses the parent's tracker
72 # (gh-80849) rather than closing it and launching its own.
73 from .resource_tracker import _fork_intent
74 _fork_intent.preserve_fd = True
75 try:
76 self.pid = os.fork()
77 finally:
78 # Reset in both parent and child so the flag does not leak
79 # into a subsequent raw os.fork() or nested Process launch.
80 _fork_intent.preserve_fd = False
81 if self.pid == 0:
82 try:
83 atexit._clear()
84 atexit.register(util._exit_function)
85 os.close(parent_r)
86 os.close(parent_w)
87 code = process_obj._bootstrap(parent_sentinel=child_r)
88 finally:
89 atexit._run_exitfuncs()
90 os._exit(code)
91 else:
92 os.close(child_w)
93 os.close(child_r)
94 self.finalizer = util.Finalize(self, util.close_fds,
95 (parent_r, parent_w,))
96 self.sentinel = parent_r
97
98 def close(self):
99 if self.finalizer is not None:
100 self.finalizer()