Python signal.SIGCHLD Examples

The following are 30 code examples for showing how to use signal.SIGCHLD(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module signal , or try the search function .

Example 1
Project: tornado-zh   Author: tao12345666333   File: process.py    License: MIT License 6 votes vote down vote up
def set_exit_callback(self, callback):
        """Runs ``callback`` when this process exits.

        The callback takes one argument, the return code of the process.

        This method uses a ``SIGCHLD`` handler, which is a global setting
        and may conflict if you have other libraries trying to handle the
        same signal.  If you are using more than one ``IOLoop`` it may
        be necessary to call `Subprocess.initialize` first to designate
        one ``IOLoop`` to run the signal handlers.

        In many cases a close callback on the stdout or stderr streams
        can be used as an alternative to an exit callback if the
        signal handler is causing a problem.
        """
        self._exit_callback = stack_context.wrap(callback)
        Subprocess.initialize(self.io_loop)
        Subprocess._waiting[self.pid] = self
        Subprocess._try_cleanup_process(self.pid) 
Example 2
Project: tornado-zh   Author: tao12345666333   File: process.py    License: MIT License 6 votes vote down vote up
def initialize(cls, io_loop=None):
        """Initializes the ``SIGCHLD`` handler.

        The signal handler is run on an `.IOLoop` to avoid locking issues.
        Note that the `.IOLoop` used for signal handling need not be the
        same one used by individual Subprocess objects (as long as the
        ``IOLoops`` are each running in separate threads).

        .. versionchanged:: 4.1
           The ``io_loop`` argument is deprecated.
        """
        if cls._initialized:
            return
        if io_loop is None:
            io_loop = ioloop.IOLoop.current()
        cls._old_sigchld = signal.signal(
            signal.SIGCHLD,
            lambda sig, frame: io_loop.add_callback_from_signal(cls._cleanup))
        cls._initialized = True 
Example 3
Project: tornado-zh   Author: tao12345666333   File: process.py    License: MIT License 6 votes vote down vote up
def set_exit_callback(self, callback):
        """Runs ``callback`` when this process exits.

        The callback takes one argument, the return code of the process.

        This method uses a ``SIGCHLD`` handler, which is a global setting
        and may conflict if you have other libraries trying to handle the
        same signal.  If you are using more than one ``IOLoop`` it may
        be necessary to call `Subprocess.initialize` first to designate
        one ``IOLoop`` to run the signal handlers.

        In many cases a close callback on the stdout or stderr streams
        can be used as an alternative to an exit callback if the
        signal handler is causing a problem.
        """
        self._exit_callback = stack_context.wrap(callback)
        Subprocess.initialize(self.io_loop)
        Subprocess._waiting[self.pid] = self
        Subprocess._try_cleanup_process(self.pid) 
Example 4
Project: benchexec   Author: sosy-lab   File: container.py    License: Apache License 2.0 6 votes vote down vote up
def wait_for_child_and_forward_signals(child_pid, process_name):
    """Wait for a child to terminate and in the meantime forward all signals
    that the current process receives to this child.
    @return a tuple of exit code and resource usage of the child as given by os.waitpid
    """
    block_all_signals()

    while True:
        logging.debug("Waiting for signals")
        signum = signal.sigwait(_ALL_SIGNALS)
        if signum == signal.SIGCHLD:
            pid, exitcode, ru_child = os.wait4(-1, os.WNOHANG)
            while pid != 0:
                if pid == child_pid:
                    return exitcode, ru_child
                else:
                    logging.debug("Received unexpected SIGCHLD for PID %s", pid)
                pid, exitcode, ru_child = os.wait4(-1, os.WNOHANG)

        else:
            _forward_signal(signum, child_pid, process_name) 
Example 5
Project: opendevops   Author: opendevops-cn   File: process.py    License: GNU General Public License v3.0 6 votes vote down vote up
def set_exit_callback(self, callback: Callable[[int], None]) -> None:
        """Runs ``callback`` when this process exits.

        The callback takes one argument, the return code of the process.

        This method uses a ``SIGCHLD`` handler, which is a global setting
        and may conflict if you have other libraries trying to handle the
        same signal.  If you are using more than one ``IOLoop`` it may
        be necessary to call `Subprocess.initialize` first to designate
        one ``IOLoop`` to run the signal handlers.

        In many cases a close callback on the stdout or stderr streams
        can be used as an alternative to an exit callback if the
        signal handler is causing a problem.

        Availability: Unix
        """
        self._exit_callback = callback
        Subprocess.initialize()
        Subprocess._waiting[self.pid] = self
        Subprocess._try_cleanup_process(self.pid) 
Example 6
Project: opendevops   Author: opendevops-cn   File: process.py    License: GNU General Public License v3.0 6 votes vote down vote up
def initialize(cls) -> None:
        """Initializes the ``SIGCHLD`` handler.

        The signal handler is run on an `.IOLoop` to avoid locking issues.
        Note that the `.IOLoop` used for signal handling need not be the
        same one used by individual Subprocess objects (as long as the
        ``IOLoops`` are each running in separate threads).

        .. versionchanged:: 5.0
           The ``io_loop`` argument (deprecated since version 4.1) has been
           removed.

        Availability: Unix
        """
        if cls._initialized:
            return
        io_loop = ioloop.IOLoop.current()
        cls._old_sigchld = signal.signal(
            signal.SIGCHLD,
            lambda sig, frame: io_loop.add_callback_from_signal(cls._cleanup),
        )
        cls._initialized = True 
Example 7
Project: viewfinder   Author: viewfinderco   File: process.py    License: Apache License 2.0 6 votes vote down vote up
def initialize(cls, io_loop=None):
        """Initializes the ``SIGCHILD`` handler.

        The signal handler is run on an `.IOLoop` to avoid locking issues.
        Note that the `.IOLoop` used for signal handling need not be the
        same one used by individual Subprocess objects (as long as the
        ``IOLoops`` are each running in separate threads).
        """
        if cls._initialized:
            return
        if io_loop is None:
            io_loop = ioloop.IOLoop.current()
        cls._old_sigchld = signal.signal(
            signal.SIGCHLD,
            lambda sig, frame: io_loop.add_callback_from_signal(cls._cleanup))
        cls._initialized = True 
Example 8
Project: viewfinder   Author: viewfinderco   File: process.py    License: Apache License 2.0 6 votes vote down vote up
def initialize(cls, io_loop=None):
        """Initializes the ``SIGCHILD`` handler.

        The signal handler is run on an `.IOLoop` to avoid locking issues.
        Note that the `.IOLoop` used for signal handling need not be the
        same one used by individual Subprocess objects (as long as the
        ``IOLoops`` are each running in separate threads).
        """
        if cls._initialized:
            return
        if io_loop is None:
            io_loop = ioloop.IOLoop.current()
        cls._old_sigchld = signal.signal(
            signal.SIGCHLD,
            lambda sig, frame: io_loop.add_callback_from_signal(cls._cleanup))
        cls._initialized = True 
Example 9
Project: cotyledon   Author: sileht   File: _utils.py    License: Apache License 2.0 6 votes vote down vote up
def __init__(self):
        # Setup signal fd, this allows signal to behave correctly
        if os.name == 'posix':
            self.signal_pipe_r, self.signal_pipe_w = os.pipe()
            self._set_nonblock(self.signal_pipe_r)
            self._set_nonblock(self.signal_pipe_w)
            signal.set_wakeup_fd(self.signal_pipe_w)

        self._signals_received = collections.deque()

        signal.signal(signal.SIGINT, signal.SIG_DFL)
        if os.name == 'posix':
            signal.signal(signal.SIGCHLD, signal.SIG_DFL)
            signal.signal(signal.SIGTERM, self._signal_catcher)
            signal.signal(signal.SIGALRM, self._signal_catcher)
            signal.signal(signal.SIGHUP, self._signal_catcher)
        else:
            # currently a noop on window...
            signal.signal(signal.SIGTERM, self._signal_catcher)
            # FIXME(sileht): should allow to catch signal CTRL_BREAK_EVENT,
            # but we to create the child process with CREATE_NEW_PROCESS_GROUP
            # to make this work, so current this is a noop for later fix
            signal.signal(signal.SIGBREAK, self._signal_catcher) 
Example 10
Project: Safejumper-for-Desktop   Author: proxysh   File: test_sigchld.py    License: GNU General Public License v2.0 6 votes vote down vote up
def setUp(self):
        """
        Save the current SIGCHLD handler as reported by L{signal.signal} and
        the current file descriptor registered with L{installHandler}.
        """
        handler = signal.getsignal(signal.SIGCHLD)
        if handler != signal.SIG_DFL:
            self.signalModuleHandler = handler
            signal.signal(signal.SIGCHLD, signal.SIG_DFL)
        else:
            self.signalModuleHandler = None

        self.oldFD = installHandler(-1)

        if self.signalModuleHandler is not None and self.oldFD != -1:
            msg("Previous test didn't clean up after its SIGCHLD setup: %r %r"
                % (self.signalModuleHandler, self.oldFD)) 
Example 11
Project: teleport   Author: tp4a   File: process.py    License: Apache License 2.0 6 votes vote down vote up
def set_exit_callback(self, callback):
        """Runs ``callback`` when this process exits.

        The callback takes one argument, the return code of the process.

        This method uses a ``SIGCHLD`` handler, which is a global setting
        and may conflict if you have other libraries trying to handle the
        same signal.  If you are using more than one ``IOLoop`` it may
        be necessary to call `Subprocess.initialize` first to designate
        one ``IOLoop`` to run the signal handlers.

        In many cases a close callback on the stdout or stderr streams
        can be used as an alternative to an exit callback if the
        signal handler is causing a problem.
        """
        self._exit_callback = stack_context.wrap(callback)
        Subprocess.initialize()
        Subprocess._waiting[self.pid] = self
        Subprocess._try_cleanup_process(self.pid) 
Example 12
Project: teleport   Author: tp4a   File: process.py    License: Apache License 2.0 6 votes vote down vote up
def initialize(cls):
        """Initializes the ``SIGCHLD`` handler.

        The signal handler is run on an `.IOLoop` to avoid locking issues.
        Note that the `.IOLoop` used for signal handling need not be the
        same one used by individual Subprocess objects (as long as the
        ``IOLoops`` are each running in separate threads).

        .. versionchanged:: 5.0
           The ``io_loop`` argument (deprecated since version 4.1) has been
           removed.
        """
        if cls._initialized:
            return
        io_loop = ioloop.IOLoop.current()
        cls._old_sigchld = signal.signal(
            signal.SIGCHLD,
            lambda sig, frame: io_loop.add_callback_from_signal(cls._cleanup))
        cls._initialized = True 
Example 13
Project: teleport   Author: tp4a   File: process.py    License: Apache License 2.0 6 votes vote down vote up
def set_exit_callback(self, callback: Callable[[int], None]) -> None:
        """Runs ``callback`` when this process exits.

        The callback takes one argument, the return code of the process.

        This method uses a ``SIGCHLD`` handler, which is a global setting
        and may conflict if you have other libraries trying to handle the
        same signal.  If you are using more than one ``IOLoop`` it may
        be necessary to call `Subprocess.initialize` first to designate
        one ``IOLoop`` to run the signal handlers.

        In many cases a close callback on the stdout or stderr streams
        can be used as an alternative to an exit callback if the
        signal handler is causing a problem.
        """
        self._exit_callback = callback
        Subprocess.initialize()
        Subprocess._waiting[self.pid] = self
        Subprocess._try_cleanup_process(self.pid) 
Example 14
Project: teleport   Author: tp4a   File: process.py    License: Apache License 2.0 6 votes vote down vote up
def set_exit_callback(self, callback: Callable[[int], None]) -> None:
        """Runs ``callback`` when this process exits.

        The callback takes one argument, the return code of the process.

        This method uses a ``SIGCHLD`` handler, which is a global setting
        and may conflict if you have other libraries trying to handle the
        same signal.  If you are using more than one ``IOLoop`` it may
        be necessary to call `Subprocess.initialize` first to designate
        one ``IOLoop`` to run the signal handlers.

        In many cases a close callback on the stdout or stderr streams
        can be used as an alternative to an exit callback if the
        signal handler is causing a problem.
        """
        self._exit_callback = callback
        Subprocess.initialize()
        Subprocess._waiting[self.pid] = self
        Subprocess._try_cleanup_process(self.pid) 
Example 15
Project: teleport   Author: tp4a   File: process.py    License: Apache License 2.0 6 votes vote down vote up
def initialize(cls) -> None:
        """Initializes the ``SIGCHLD`` handler.

        The signal handler is run on an `.IOLoop` to avoid locking issues.
        Note that the `.IOLoop` used for signal handling need not be the
        same one used by individual Subprocess objects (as long as the
        ``IOLoops`` are each running in separate threads).

        .. versionchanged:: 5.0
           The ``io_loop`` argument (deprecated since version 4.1) has been
           removed.
        """
        if cls._initialized:
            return
        io_loop = ioloop.IOLoop.current()
        cls._old_sigchld = signal.signal(
            signal.SIGCHLD,
            lambda sig, frame: io_loop.add_callback_from_signal(cls._cleanup),
        )
        cls._initialized = True 
Example 16
Project: pycopia   Author: kdart   File: proctools.py    License: Apache License 2.0 6 votes vote down vote up
def clone(self, proc=None):
        """clone([proc]) clones the supplied process object and manages it as
        well. If no process object is supplied then clone the first managed
        process found in this ProcManager.
        """
        if proc is None: # default to cloning first process found.
            procs = self._procs.values()
            if procs:
                proc = procs[0]
                del procs
            else:
                return
        signal.signal(SIGCHLD, SIG_DFL) # critical area
        newproc = proc.clone()
        self._procs[newproc.childpid] = newproc
        signal.signal(SIGCHLD, self._child_handler)
        signal.siginterrupt(SIGCHLD, False)
        return newproc 
Example 17
Project: prjxray   Author: SymbiFlow   File: run_fuzzer.py    License: ISC License 6 votes vote down vote up
def get_usage():
    # This function only works if you have a signal handler for the
    # signal.SIGCHLD signal.
    raw_usage = resource.getrusage(resource.RUSAGE_CHILDREN)
    # 0   ru_utime    time in user mode (float)
    # 1   ru_stime    time in system mode (float)
    # 2   ru_maxrss   maximum resident set size
    #
    # These fields are always zero on Linux
    # 3   ru_ixrss    shared memory size
    # 4   ru_idrss    unshared memory size
    # 5   ru_isrss    unshared stack size
    return "User:{}s System:{}s".format(
        int(raw_usage.ru_utime),
        int(raw_usage.ru_stime),
    ) 
Example 18
Project: prjxray   Author: SymbiFlow   File: run_fuzzer.py    License: ISC License 6 votes vote down vote up
def get_usage():
    # This function only works if you have a signal handler for the
    # signal.SIGCHLD signal.
    raw_usage = resource.getrusage(resource.RUSAGE_CHILDREN)
    # 0   ru_utime    time in user mode (float)
    # 1   ru_stime    time in system mode (float)
    # 2   ru_maxrss   maximum resident set size
    #
    # These fields are always zero on Linux
    # 3   ru_ixrss    shared memory size
    # 4   ru_idrss    unshared memory size
    # 5   ru_isrss    unshared stack size
    return "User:{}s System:{}s".format(
        int(raw_usage.ru_utime),
        int(raw_usage.ru_stime),
    ) 
Example 19
Project: pySINDy   Author: luckystarufo   File: process.py    License: MIT License 6 votes vote down vote up
def set_exit_callback(self, callback):
        """Runs ``callback`` when this process exits.

        The callback takes one argument, the return code of the process.

        This method uses a ``SIGCHLD`` handler, which is a global setting
        and may conflict if you have other libraries trying to handle the
        same signal.  If you are using more than one ``IOLoop`` it may
        be necessary to call `Subprocess.initialize` first to designate
        one ``IOLoop`` to run the signal handlers.

        In many cases a close callback on the stdout or stderr streams
        can be used as an alternative to an exit callback if the
        signal handler is causing a problem.
        """
        self._exit_callback = stack_context.wrap(callback)
        Subprocess.initialize()
        Subprocess._waiting[self.pid] = self
        Subprocess._try_cleanup_process(self.pid) 
Example 20
Project: pySINDy   Author: luckystarufo   File: process.py    License: MIT License 6 votes vote down vote up
def initialize(cls):
        """Initializes the ``SIGCHLD`` handler.

        The signal handler is run on an `.IOLoop` to avoid locking issues.
        Note that the `.IOLoop` used for signal handling need not be the
        same one used by individual Subprocess objects (as long as the
        ``IOLoops`` are each running in separate threads).

        .. versionchanged:: 5.0
           The ``io_loop`` argument (deprecated since version 4.1) has been
           removed.
        """
        if cls._initialized:
            return
        io_loop = ioloop.IOLoop.current()
        cls._old_sigchld = signal.signal(
            signal.SIGCHLD,
            lambda sig, frame: io_loop.add_callback_from_signal(cls._cleanup))
        cls._initialized = True 
Example 21
Project: Imogen   Author: CedricGuillemet   File: unix_events.py    License: MIT License 6 votes vote down vote up
def attach_loop(self, loop):
        assert loop is None or isinstance(loop, events.AbstractEventLoop)

        if self._loop is not None and loop is None and self._callbacks:
            warnings.warn(
                'A loop is being detached '
                'from a child watcher with pending handlers',
                RuntimeWarning)

        if self._loop is not None:
            self._loop.remove_signal_handler(signal.SIGCHLD)

        self._loop = loop
        if loop is not None:
            loop.add_signal_handler(signal.SIGCHLD, self._sig_chld)

            # Prevent a race condition in case a child terminated
            # during the switch.
            self._do_waitpid_all() 
Example 22
Project: learn_python3_spider   Author: wistbean   File: test_sigchld.py    License: MIT License 6 votes vote down vote up
def setUp(self):
        """
        Save the current SIGCHLD handler as reported by L{signal.signal} and
        the current file descriptor registered with L{installHandler}.
        """
        handler = signal.getsignal(signal.SIGCHLD)
        if handler != signal.SIG_DFL:
            self.signalModuleHandler = handler
            signal.signal(signal.SIGCHLD, signal.SIG_DFL)
        else:
            self.signalModuleHandler = None

        self.oldFD = installHandler(-1)

        if self.signalModuleHandler is not None and self.oldFD != -1:
            msg("Previous test didn't clean up after its SIGCHLD setup: %r %r"
                % (self.signalModuleHandler, self.oldFD)) 
Example 23
Project: tornado-zh   Author: tao12345666333   File: process.py    License: MIT License 5 votes vote down vote up
def uninitialize(cls):
        """Removes the ``SIGCHLD`` handler."""
        if not cls._initialized:
            return
        signal.signal(signal.SIGCHLD, cls._old_sigchld)
        cls._initialized = False 
Example 24
Project: tornado-zh   Author: tao12345666333   File: twisted_test.py    License: MIT License 5 votes vote down vote up
def save_signal_handlers():
    saved = {}
    for sig in [signal.SIGINT, signal.SIGTERM, signal.SIGCHLD]:
        saved[sig] = signal.getsignal(sig)
    if "twisted" in repr(saved):
        if not issubclass(IOLoop.configured_class(), TwistedIOLoop):
            # when the global ioloop is twisted, we expect the signal
            # handlers to be installed.  Otherwise, it means we're not
            # cleaning up after twisted properly.
            raise Exception("twisted signal handlers already installed")
    return saved 
Example 25
Project: tornado-zh   Author: tao12345666333   File: process.py    License: MIT License 5 votes vote down vote up
def uninitialize(cls):
        """Removes the ``SIGCHLD`` handler."""
        if not cls._initialized:
            return
        signal.signal(signal.SIGCHLD, cls._old_sigchld)
        cls._initialized = False 
Example 26
Project: tornado-zh   Author: tao12345666333   File: twisted_test.py    License: MIT License 5 votes vote down vote up
def save_signal_handlers():
    saved = {}
    for sig in [signal.SIGINT, signal.SIGTERM, signal.SIGCHLD]:
        saved[sig] = signal.getsignal(sig)
    if "twisted" in repr(saved):
        if not issubclass(IOLoop.configured_class(), TwistedIOLoop):
            # when the global ioloop is twisted, we expect the signal
            # handlers to be installed.  Otherwise, it means we're not
            # cleaning up after twisted properly.
            raise Exception("twisted signal handlers already installed")
    return saved 
Example 27
Project: ffw   Author: dobin   File: debugservermanager.py    License: GNU General Public License v3.0 5 votes vote down vote up
def _waitForCrash(self):
        while True:
            logging.info("ServerManager: Debug: Waiting for process event")
            event = self.dbg.waitProcessEvent()
            logging.info("ServerManager: Debug: " + str(event))
            # If this is a process exit we need to check if it was abnormal
            if type(event) == ProcessExit:
                if event.signum is None or event.exitcode == 0:
                    # Clear the event since this was a normal exit
                    event = None

            # If this is a signal we need to check if we're ignoring it
            elif type(event) == ProcessSignal:
                if event.signum == signal.SIGCHLD:
                    # Ignore these signals and continue waiting
                    continue
                elif event.signum == signal.SIGTERM:
                    # server cannot be started, return
                    event = None
                    self.queue_sync.put( ("err", event.signum) )

            break

        if event is not None and event.signum != 15:
            logging.info("ServerManager: Debug: Event Result: Crash")
            self.crashEvent = event
            return True
        else:
            logging.info("ServerManager: Debug: Event Result: No crash")
            self.crashEvent = None
            return False 
Example 28
Project: agentless-system-crawler   Author: cloudviz   File: fprobe_container_crawler.py    License: Apache License 2.0 5 votes vote down vote up
def start_fprobe(self, ifname, user, bindaddr, port, **kwargs):
        """
          Start the flow probe process on the given interface;
          use the bindaddr and port as the collector.
          This function returns the process ID of the started process
          and an errcode (errno) in case an error was encountered in
          the start_child function.
        """
        maxlife_timeout = get_uint_arg('maxlife_timeout', 30, **kwargs)
        netflow_version = get_uint_arg('netflow_version', 5, **kwargs)
        if netflow_version not in [1, 5, 9, 10]:
            logger.info('Unsupported netflow version was chosen: %d' %
                        netflow_version)
            netflow_version = 5

        terminate_process = kwargs.get('terminate_fprobe', 'FALSE').upper()
        setsid = terminate_process in ['0', 'FALSE']
        fprobe_bpf = kwargs.get('fprobe_bpf', '')

        params = ['softflowd',
                  '-i', ifname,
                  '-v', '%d' % netflow_version,
                  '-d',
                  '-t', 'maxlife=%d' % maxlife_timeout,
                  '-n', '%s:%d' % (bindaddr, port)]
        if len(fprobe_bpf.strip()):
            params.insert(1, fprobe_bpf)
        if netflow_version == 10:
            params.insert(1, '-b')
        try:
            pid, errcode = start_child(params, [], [0, 1, 2],
                                       [signal.SIGCHLD],
                                       setsid=setsid,
                                       max_close_fd=128)
            logger.info('Started softflowd as pid %d' % pid)
        except:
            pid = -1
            errcode = errno.EINVAL

        return pid, errcode 
Example 29
Project: agentless-system-crawler   Author: cloudviz   File: fprobe_container_crawler.py    License: Apache License 2.0 5 votes vote down vote up
def start_collector(self, user, socket, output_dir, watch_pid, metadata,
                        **kwargs):
        """
          Start the collector process; have it drop privileges by
          switching to the given user; have it write the data to the
          output_dir and use a filename pattern given by
          filenamepattern; have it watch the process with the given
          watch_pid
        """
        filepattern = kwargs.get('output_filepattern',
                                 'fprobe-{ifname}-{timestamp}')

        params = ['socket-datacollector',
                  '--user', user,
                  '--sockfd', str(socket.fileno()),
                  '--dir', output_dir,
                  '--filepattern', filepattern,
                  '--watch-pid', str(watch_pid),
                  '--metadata', json.dumps(metadata),
                  '--md-filter', 'ip-addresses']
        try:
            pid, errcode = start_child(params, [socket.fileno()], [],
                                       [signal.SIGCHLD],
                                       setsid=True,
                                       max_close_fd=128)
            logger.info('Started collector as pid %d' % pid)
        except:
            pid = -1
            errcode = errno.EINVAL

        return pid, errcode 
Example 30
Project: opendevops   Author: opendevops-cn   File: process.py    License: GNU General Public License v3.0 5 votes vote down vote up
def uninitialize(cls) -> None:
        """Removes the ``SIGCHLD`` handler."""
        if not cls._initialized:
            return
        signal.signal(signal.SIGCHLD, cls._old_sigchld)
        cls._initialized = False