jpayne@69: # jpayne@69: # Module providing the `Process` class which emulates `threading.Thread` jpayne@69: # jpayne@69: # multiprocessing/process.py jpayne@69: # jpayne@69: # Copyright (c) 2006-2008, R Oudkerk jpayne@69: # Licensed to PSF under a Contributor Agreement. jpayne@69: # jpayne@69: jpayne@69: __all__ = ['BaseProcess', 'current_process', 'active_children', jpayne@69: 'parent_process'] jpayne@69: jpayne@69: # jpayne@69: # Imports jpayne@69: # jpayne@69: jpayne@69: import os jpayne@69: import sys jpayne@69: import signal jpayne@69: import itertools jpayne@69: import threading jpayne@69: from _weakrefset import WeakSet jpayne@69: jpayne@69: # jpayne@69: # jpayne@69: # jpayne@69: jpayne@69: try: jpayne@69: ORIGINAL_DIR = os.path.abspath(os.getcwd()) jpayne@69: except OSError: jpayne@69: ORIGINAL_DIR = None jpayne@69: jpayne@69: # jpayne@69: # Public functions jpayne@69: # jpayne@69: jpayne@69: def current_process(): jpayne@69: ''' jpayne@69: Return process object representing the current process jpayne@69: ''' jpayne@69: return _current_process jpayne@69: jpayne@69: def active_children(): jpayne@69: ''' jpayne@69: Return list of process objects corresponding to live child processes jpayne@69: ''' jpayne@69: _cleanup() jpayne@69: return list(_children) jpayne@69: jpayne@69: jpayne@69: def parent_process(): jpayne@69: ''' jpayne@69: Return process object representing the parent process jpayne@69: ''' jpayne@69: return _parent_process jpayne@69: jpayne@69: # jpayne@69: # jpayne@69: # jpayne@69: jpayne@69: def _cleanup(): jpayne@69: # check for processes which have finished jpayne@69: for p in list(_children): jpayne@69: if p._popen.poll() is not None: jpayne@69: _children.discard(p) jpayne@69: jpayne@69: # jpayne@69: # The `Process` class jpayne@69: # jpayne@69: jpayne@69: class BaseProcess(object): jpayne@69: ''' jpayne@69: Process objects represent activity that is run in a separate process jpayne@69: jpayne@69: The class is analogous to `threading.Thread` jpayne@69: ''' jpayne@69: def _Popen(self): jpayne@69: raise NotImplementedError jpayne@69: jpayne@69: def __init__(self, group=None, target=None, name=None, args=(), kwargs={}, jpayne@69: *, daemon=None): jpayne@69: assert group is None, 'group argument must be None for now' jpayne@69: count = next(_process_counter) jpayne@69: self._identity = _current_process._identity + (count,) jpayne@69: self._config = _current_process._config.copy() jpayne@69: self._parent_pid = os.getpid() jpayne@69: self._parent_name = _current_process.name jpayne@69: self._popen = None jpayne@69: self._closed = False jpayne@69: self._target = target jpayne@69: self._args = tuple(args) jpayne@69: self._kwargs = dict(kwargs) jpayne@69: self._name = name or type(self).__name__ + '-' + \ jpayne@69: ':'.join(str(i) for i in self._identity) jpayne@69: if daemon is not None: jpayne@69: self.daemon = daemon jpayne@69: _dangling.add(self) jpayne@69: jpayne@69: def _check_closed(self): jpayne@69: if self._closed: jpayne@69: raise ValueError("process object is closed") jpayne@69: jpayne@69: def run(self): jpayne@69: ''' jpayne@69: Method to be run in sub-process; can be overridden in sub-class jpayne@69: ''' jpayne@69: if self._target: jpayne@69: self._target(*self._args, **self._kwargs) jpayne@69: jpayne@69: def start(self): jpayne@69: ''' jpayne@69: Start child process jpayne@69: ''' jpayne@69: self._check_closed() jpayne@69: assert self._popen is None, 'cannot start a process twice' jpayne@69: assert self._parent_pid == os.getpid(), \ jpayne@69: 'can only start a process object created by current process' jpayne@69: assert not _current_process._config.get('daemon'), \ jpayne@69: 'daemonic processes are not allowed to have children' jpayne@69: _cleanup() jpayne@69: self._popen = self._Popen(self) jpayne@69: self._sentinel = self._popen.sentinel jpayne@69: # Avoid a refcycle if the target function holds an indirect jpayne@69: # reference to the process object (see bpo-30775) jpayne@69: del self._target, self._args, self._kwargs jpayne@69: _children.add(self) jpayne@69: jpayne@69: def terminate(self): jpayne@69: ''' jpayne@69: Terminate process; sends SIGTERM signal or uses TerminateProcess() jpayne@69: ''' jpayne@69: self._check_closed() jpayne@69: self._popen.terminate() jpayne@69: jpayne@69: def kill(self): jpayne@69: ''' jpayne@69: Terminate process; sends SIGKILL signal or uses TerminateProcess() jpayne@69: ''' jpayne@69: self._check_closed() jpayne@69: self._popen.kill() jpayne@69: jpayne@69: def join(self, timeout=None): jpayne@69: ''' jpayne@69: Wait until child process terminates jpayne@69: ''' jpayne@69: self._check_closed() jpayne@69: assert self._parent_pid == os.getpid(), 'can only join a child process' jpayne@69: assert self._popen is not None, 'can only join a started process' jpayne@69: res = self._popen.wait(timeout) jpayne@69: if res is not None: jpayne@69: _children.discard(self) jpayne@69: jpayne@69: def is_alive(self): jpayne@69: ''' jpayne@69: Return whether process is alive jpayne@69: ''' jpayne@69: self._check_closed() jpayne@69: if self is _current_process: jpayne@69: return True jpayne@69: assert self._parent_pid == os.getpid(), 'can only test a child process' jpayne@69: jpayne@69: if self._popen is None: jpayne@69: return False jpayne@69: jpayne@69: returncode = self._popen.poll() jpayne@69: if returncode is None: jpayne@69: return True jpayne@69: else: jpayne@69: _children.discard(self) jpayne@69: return False jpayne@69: jpayne@69: def close(self): jpayne@69: ''' jpayne@69: Close the Process object. jpayne@69: jpayne@69: This method releases resources held by the Process object. It is jpayne@69: an error to call this method if the child process is still running. jpayne@69: ''' jpayne@69: if self._popen is not None: jpayne@69: if self._popen.poll() is None: jpayne@69: raise ValueError("Cannot close a process while it is still running. " jpayne@69: "You should first call join() or terminate().") jpayne@69: self._popen.close() jpayne@69: self._popen = None jpayne@69: del self._sentinel jpayne@69: _children.discard(self) jpayne@69: self._closed = True jpayne@69: jpayne@69: @property jpayne@69: def name(self): jpayne@69: return self._name jpayne@69: jpayne@69: @name.setter jpayne@69: def name(self, name): jpayne@69: assert isinstance(name, str), 'name must be a string' jpayne@69: self._name = name jpayne@69: jpayne@69: @property jpayne@69: def daemon(self): jpayne@69: ''' jpayne@69: Return whether process is a daemon jpayne@69: ''' jpayne@69: return self._config.get('daemon', False) jpayne@69: jpayne@69: @daemon.setter jpayne@69: def daemon(self, daemonic): jpayne@69: ''' jpayne@69: Set whether process is a daemon jpayne@69: ''' jpayne@69: assert self._popen is None, 'process has already started' jpayne@69: self._config['daemon'] = daemonic jpayne@69: jpayne@69: @property jpayne@69: def authkey(self): jpayne@69: return self._config['authkey'] jpayne@69: jpayne@69: @authkey.setter jpayne@69: def authkey(self, authkey): jpayne@69: ''' jpayne@69: Set authorization key of process jpayne@69: ''' jpayne@69: self._config['authkey'] = AuthenticationString(authkey) jpayne@69: jpayne@69: @property jpayne@69: def exitcode(self): jpayne@69: ''' jpayne@69: Return exit code of process or `None` if it has yet to stop jpayne@69: ''' jpayne@69: self._check_closed() jpayne@69: if self._popen is None: jpayne@69: return self._popen jpayne@69: return self._popen.poll() jpayne@69: jpayne@69: @property jpayne@69: def ident(self): jpayne@69: ''' jpayne@69: Return identifier (PID) of process or `None` if it has yet to start jpayne@69: ''' jpayne@69: self._check_closed() jpayne@69: if self is _current_process: jpayne@69: return os.getpid() jpayne@69: else: jpayne@69: return self._popen and self._popen.pid jpayne@69: jpayne@69: pid = ident jpayne@69: jpayne@69: @property jpayne@69: def sentinel(self): jpayne@69: ''' jpayne@69: Return a file descriptor (Unix) or handle (Windows) suitable for jpayne@69: waiting for process termination. jpayne@69: ''' jpayne@69: self._check_closed() jpayne@69: try: jpayne@69: return self._sentinel jpayne@69: except AttributeError: jpayne@69: raise ValueError("process not started") from None jpayne@69: jpayne@69: def __repr__(self): jpayne@69: exitcode = None jpayne@69: if self is _current_process: jpayne@69: status = 'started' jpayne@69: elif self._closed: jpayne@69: status = 'closed' jpayne@69: elif self._parent_pid != os.getpid(): jpayne@69: status = 'unknown' jpayne@69: elif self._popen is None: jpayne@69: status = 'initial' jpayne@69: else: jpayne@69: exitcode = self._popen.poll() jpayne@69: if exitcode is not None: jpayne@69: status = 'stopped' jpayne@69: else: jpayne@69: status = 'started' jpayne@69: jpayne@69: info = [type(self).__name__, 'name=%r' % self._name] jpayne@69: if self._popen is not None: jpayne@69: info.append('pid=%s' % self._popen.pid) jpayne@69: info.append('parent=%s' % self._parent_pid) jpayne@69: info.append(status) jpayne@69: if exitcode is not None: jpayne@69: exitcode = _exitcode_to_name.get(exitcode, exitcode) jpayne@69: info.append('exitcode=%s' % exitcode) jpayne@69: if self.daemon: jpayne@69: info.append('daemon') jpayne@69: return '<%s>' % ' '.join(info) jpayne@69: jpayne@69: ## jpayne@69: jpayne@69: def _bootstrap(self, parent_sentinel=None): jpayne@69: from . import util, context jpayne@69: global _current_process, _parent_process, _process_counter, _children jpayne@69: jpayne@69: try: jpayne@69: if self._start_method is not None: jpayne@69: context._force_start_method(self._start_method) jpayne@69: _process_counter = itertools.count(1) jpayne@69: _children = set() jpayne@69: util._close_stdin() jpayne@69: old_process = _current_process jpayne@69: _current_process = self jpayne@69: _parent_process = _ParentProcess( jpayne@69: self._parent_name, self._parent_pid, parent_sentinel) jpayne@69: if threading._HAVE_THREAD_NATIVE_ID: jpayne@69: threading.main_thread()._set_native_id() jpayne@69: try: jpayne@69: util._finalizer_registry.clear() jpayne@69: util._run_after_forkers() jpayne@69: finally: jpayne@69: # delay finalization of the old process object until after jpayne@69: # _run_after_forkers() is executed jpayne@69: del old_process jpayne@69: util.info('child process calling self.run()') jpayne@69: try: jpayne@69: self.run() jpayne@69: exitcode = 0 jpayne@69: finally: jpayne@69: util._exit_function() jpayne@69: except SystemExit as e: jpayne@69: if not e.args: jpayne@69: exitcode = 1 jpayne@69: elif isinstance(e.args[0], int): jpayne@69: exitcode = e.args[0] jpayne@69: else: jpayne@69: sys.stderr.write(str(e.args[0]) + '\n') jpayne@69: exitcode = 1 jpayne@69: except: jpayne@69: exitcode = 1 jpayne@69: import traceback jpayne@69: sys.stderr.write('Process %s:\n' % self.name) jpayne@69: traceback.print_exc() jpayne@69: finally: jpayne@69: threading._shutdown() jpayne@69: util.info('process exiting with exitcode %d' % exitcode) jpayne@69: util._flush_std_streams() jpayne@69: jpayne@69: return exitcode jpayne@69: jpayne@69: # jpayne@69: # We subclass bytes to avoid accidental transmission of auth keys over network jpayne@69: # jpayne@69: jpayne@69: class AuthenticationString(bytes): jpayne@69: def __reduce__(self): jpayne@69: from .context import get_spawning_popen jpayne@69: if get_spawning_popen() is None: jpayne@69: raise TypeError( jpayne@69: 'Pickling an AuthenticationString object is ' jpayne@69: 'disallowed for security reasons' jpayne@69: ) jpayne@69: return AuthenticationString, (bytes(self),) jpayne@69: jpayne@69: jpayne@69: # jpayne@69: # Create object representing the parent process jpayne@69: # jpayne@69: jpayne@69: class _ParentProcess(BaseProcess): jpayne@69: jpayne@69: def __init__(self, name, pid, sentinel): jpayne@69: self._identity = () jpayne@69: self._name = name jpayne@69: self._pid = pid jpayne@69: self._parent_pid = None jpayne@69: self._popen = None jpayne@69: self._closed = False jpayne@69: self._sentinel = sentinel jpayne@69: self._config = {} jpayne@69: jpayne@69: def is_alive(self): jpayne@69: from multiprocessing.connection import wait jpayne@69: return not wait([self._sentinel], timeout=0) jpayne@69: jpayne@69: @property jpayne@69: def ident(self): jpayne@69: return self._pid jpayne@69: jpayne@69: def join(self, timeout=None): jpayne@69: ''' jpayne@69: Wait until parent process terminates jpayne@69: ''' jpayne@69: from multiprocessing.connection import wait jpayne@69: wait([self._sentinel], timeout=timeout) jpayne@69: jpayne@69: pid = ident jpayne@69: jpayne@69: # jpayne@69: # Create object representing the main process jpayne@69: # jpayne@69: jpayne@69: class _MainProcess(BaseProcess): jpayne@69: jpayne@69: def __init__(self): jpayne@69: self._identity = () jpayne@69: self._name = 'MainProcess' jpayne@69: self._parent_pid = None jpayne@69: self._popen = None jpayne@69: self._closed = False jpayne@69: self._config = {'authkey': AuthenticationString(os.urandom(32)), jpayne@69: 'semprefix': '/mp'} jpayne@69: # Note that some versions of FreeBSD only allow named jpayne@69: # semaphores to have names of up to 14 characters. Therefore jpayne@69: # we choose a short prefix. jpayne@69: # jpayne@69: # On MacOSX in a sandbox it may be necessary to use a jpayne@69: # different prefix -- see #19478. jpayne@69: # jpayne@69: # Everything in self._config will be inherited by descendant jpayne@69: # processes. jpayne@69: jpayne@69: def close(self): jpayne@69: pass jpayne@69: jpayne@69: jpayne@69: _parent_process = None jpayne@69: _current_process = _MainProcess() jpayne@69: _process_counter = itertools.count(1) jpayne@69: _children = set() jpayne@69: del _MainProcess jpayne@69: jpayne@69: # jpayne@69: # Give names to some return codes jpayne@69: # jpayne@69: jpayne@69: _exitcode_to_name = {} jpayne@69: jpayne@69: for name, signum in list(signal.__dict__.items()): jpayne@69: if name[:3]=='SIG' and '_' not in name: jpayne@69: _exitcode_to_name[-signum] = f'-{name}' jpayne@69: jpayne@69: # For debug and leak testing jpayne@69: _dangling = WeakSet()