Handle SIGUSR1 signal. Call function which is defined in the
        **settings.SIGUSR1_HANDLER**. If main process, forward the
        signal to all child processes.
187866
def sigusr1_handler(self, unused_signum, unused_frame):
        
        for process in self.processes:
            if process.pid and os.getpid() == self.main_pid:
                try:
                    os.kill(process.pid, signal.SIGUSR1)
                except ProcessLookupError:
                    pass
        if self._sigusr1_handler_func is not None:
            self._sigusr1_handler_func(self.context)
967008
def subprocess_func(func, pipe, logger, mem_in_mb, cpu_time_limit_in_s, wall_time_limit_in_s, num_procs, grace_period_in_s, tmp_dir, *args, **kwargs):

	# simple signal handler to catch the signals for time limits
	def handler(signum, frame):
		# logs message with level debug on this logger 
		logger.debug("signal handler: %i"%signum)
		if (signum == signal.SIGXCPU):
			# when process reaches soft limit --> a SIGXCPU signal is sent (it normally terminats the process)
			raise(CpuTimeoutException)
		elif (signum == signal.SIGALRM):
			# SIGALRM is sent to process when the specified time limit to an alarm function elapses (when real or clock time elapses)
			logger.debug("timeout")
			raise(TimeoutException)
		raise AnythingException

	# temporary directory to store stdout and stderr
	if not tmp_dir is None:
		logger.debug('Redirecting output of the function to files. Access them via the stdout and stderr attributes of the wrapped function.')
		
		stdout = open(os.path.join(tmp_dir, 'std.out'), 'a', buffering=1)
		sys.stdout=stdout

		stderr = open(os.path.join(tmp_dir, 'std.err'), 'a', buffering=1)
		sys.stderr=stderr


	# catching all signals at this point turned out to interfer with the subprocess (e.g. using ROS)
	signal.signal(signal.SIGALRM, handler)
	signal.signal(signal.SIGXCPU, handler)
	signal.signal(signal.SIGQUIT, handler)

	# code to catch EVERY catchable signal (even X11 related ones ... )
	# only use for debugging/testing as this seems to be too intrusive.
	

	# set the memory limit
	if mem_in_mb is not None:
		# byte --> megabyte
		mem_in_b = mem_in_mb*1024*1024
		# the maximum area (in bytes) of address space which may be taken by the process.
		resource.setrlimit(resource.RLIMIT_AS, (mem_in_b, mem_in_b))

	# for now: don't allow the function to spawn subprocesses itself.
	#resource.setrlimit(resource.RLIMIT_NPROC, (1, 1))
	# Turns out, this is quite restrictive, so we don't use this option by default
	if num_procs is not None:
		resource.setrlimit(resource.RLIMIT_NPROC, (num_procs, num_procs))


	# schedule an alarm in specified number of seconds
	if wall_time_limit_in_s is not None:
		signal.alarm(wall_time_limit_in_s)
	
	if cpu_time_limit_in_s is not None:
		# From the Linux man page:
		# When the process reaches the soft limit, it is sent a SIGXCPU signal.
		# The default action for this signal is to terminate the process.
		# However, the signal can be caught, and the handler can return control 
		# to the main program. If the process continues to consume CPU time,
		# it will be sent SIGXCPU once per second until the hard limit is reached,
		# at which time it is sent SIGKILL.
		resource.setrlimit(resource.RLIMIT_CPU, (cpu_time_limit_in_s,cpu_time_limit_in_s+grace_period_in_s))

	# the actual function call
	try:
		logger.debug("call function")
		return_value = ((func(*args, **kwargs), 0))
		logger.debug("function returned properly: {}".format(return_value))
	except MemoryError:
		return_value = (None, MemorylimitException)

	except OSError as e:
		if (e.errno == 11):
			return_value = (None, SubprocessException)
		else:
			return_value = (None, AnythingException)

	except CpuTimeoutException:
		return_value = (None, CpuTimeoutException)

	except TimeoutException:
		return_value = (None, TimeoutException)

	except AnythingException as e:
		return_value = (None, AnythingException)
	except:
		raise
		logger.debug("Some wired exception occured!")
		
	finally:
		try:
			logger.debug("return value: {}".format(return_value))
			
			pipe.send(return_value)
			pipe.close()

		except:
			# this part should only fail if the parent process is alread dead, so there is not much to do anymore :)
			pass
		finally:
			# recursively kill all children
			p = psutil.Process()
			for child in p.children(recursive=True):
				child.kill()
708212
def salt_minion():
    '''
    
    '''
    import signal

    import salt.utils.platform
    import salt.utils.process
    salt.utils.process.notify_systemd()

    import salt.cli.daemons
    import multiprocessing
    if '' in sys.path:
        sys.path.remove('')

    if salt.utils.platform.is_windows():
        minion = salt.cli.daemons.Minion()
        minion.start()
        return
# REMOVEME after Python 2.7 support is dropped (also the six import)
    elif six.PY2:
        from salt.utils.versions import warn_until
        # Message borrowed from pip's deprecation warning
        warn_until('Sodium',
                   'Python 2.7 will reach the end of its life on January 1st,'
                   ' 2020. Please upgrade your Python as Python 2.7 won\'t be'
                   ' maintained after that date.  Salt will drop support for'
                   ' Python 2.7 in the Sodium release or later.')
# END REMOVEME

    if '--disable-keepalive' in sys.argv:
        sys.argv.remove('--disable-keepalive')
        minion = salt.cli.daemons.Minion()
        minion.start()
        return

    def escalate_signal_to_process(pid, signum, sigframe):  # pylint: disable=unused-argument
        '''
        Escalate the signal received to the multiprocessing process that
        is actually running the minion
        '''
        # escalate signal
        os.kill(pid, signum)

    # keep one minion subprocess running
    prev_sigint_handler = signal.getsignal(signal.SIGINT)
    prev_sigterm_handler = signal.getsignal(signal.SIGTERM)
    while True:
        try:
            process = multiprocessing.Process(target=minion_process)
            process.start()
            signal.signal(signal.SIGTERM,
                          functools.partial(escalate_signal_to_process,
                                            process.pid))
            signal.signal(signal.SIGINT,
                          functools.partial(escalate_signal_to_process,
                                            process.pid))
            signal.signal(signal.SIGHUP,
                          functools.partial(escalate_signal_to_process,
                                            process.pid))
        except Exception:  # pylint: disable=broad-except
            # if multiprocessing does not work
            minion = salt.cli.daemons.Minion()
            minion.start()
            break

        process.join()

        # Process exited or was terminated. Since we're going to try to restart
        # it, we MUST, reset signal handling to the previous handlers
        signal.signal(signal.SIGINT, prev_sigint_handler)
        signal.signal(signal.SIGTERM, prev_sigterm_handler)

        if not process.exitcode == salt.defaults.exitcodes.SALT_KEEPALIVE:
            sys.exit(process.exitcode)
        # ontop of the random_reauth_delay already preformed
        # delay extra to reduce flooding and free resources
        # NOTE: values are static but should be fine.
        time.sleep(2 + randint(1, 10))
        # need to reset logging because new minion objects
        # cause extra log handlers to accumulate
        rlogger = logging.getLogger()
        for handler in rlogger.handlers:
            rlogger.removeHandler(handler)
        logging.basicConfig()
171744
def signal_handler(self, *args):
        
        self.user_callback(self.signal, self.user_arg, *args)
1228628
def _sig_handler(self, signum, stack):
        '''
        
        '''
        log_debug("Got SIGINT.")
        if signum == signal.SIGINT:
            LLNetReal.running = False
            if self._pktqueue.qsize() == 0:
                # put dummy pkt in queue to unblock a 
                # possibly stuck user thread
                self._pktqueue.put( (None,None,None) )
677375
def main():
    
    # Setup an initial logging handler that buffers log messages before
    # applying the final logging configuration.
    initial_handler = logging.handlers.MemoryHandler(100)
    root_logger = logging.getLogger()
    root_logger.addHandler(initial_handler)

    # Parse configuration and setup logging.
    conf = config.Config(get_config_options())
    conf.parse_args()
    setup_logging(conf)

    # Flush the buffered log messages to the final logging handler.
    initial_handler.setTarget(root_logger.handlers[-1])
    initial_handler.flush()
    root_logger.removeHandler(initial_handler)

    log_startup_info()

    connector = Connector.from_config(conf)

    # Catch SIGTERM and SIGINT to cleanup the connector gracefully
    def signame_handler(signal_name):
        def sig_handler(signum, frame):
            # Save the signal so it can be printed later
            connector.signal = (signal_name, signum)
            connector.can_run = False

        return sig_handler

    signal.signal(signal.SIGTERM, signame_handler("SIGTERM"))
    signal.signal(signal.SIGINT, signame_handler("SIGINT"))

    connector.start()

    while True:
        if not connector.is_alive():
            break
        time.sleep(3)
792296
def __watchers_callbacks_exec(self, signal_name):
		
		def callback_fn():
			for watcher in self.__watchers_callbacks[signal_name]:
				if watcher is not None:
					watcher.notify()
		return callback_fn
535340
def sig_handler(self, sig, _):
        
        import tornado.ioloop
        from tornado.process import task_id
        tid = task_id()
        pid = os.getpid()
        if tid is None:
            logger.warning("main process (pid %s) caught signal: %s" %
                           (pid, sig))
        else:
            logger.warning("child %s (pid %s) caught signal: %s" %
                           (tid, pid, sig))
        tornado.ioloop.IOLoop.current().add_callback(self.shutdown)
1360325
def signal_catcher(callback):
    """"""
    def _catch_exit_signal(sig_num, _frame):
        print('Received signal {:d} invoking callback...'.format(sig_num))
        callback()

    signal.signal(signal.SIGINT, _catch_exit_signal)
    signal.signal(signal.SIGQUIT, _catch_exit_signal)
    signal.signal(signal.SIGTERM, _catch_exit_signal)
    yield
479757
def _main(self):
        
        self.set_proctitle(self.name)
        self.set_signal_handler()

        logger.info("process for module %s is now running (pid=%d)", self.name, os.getpid())

        # Will block here!
        try:
            self.main()
        except (IOError, EOFError):
            pass
            # logger.warning('[%s] EOF exception: %s', self.name, traceback.format_exc())
        except Exception as exp:  # pylint: disable=broad-except
            logger.exception('main function exception: %s', exp)

        self.do_stop()

        logger.info("process for module %s is now exiting (pid=%d)", self.name, os.getpid())
        exit()
1174468
def run(self):
        
        setproctitle.setproctitle("{:s}: {:s}".format(
            self.context.config.name, self.__class__.__name__))
        self.logger.info(
            "Worker '%s' has been started with pid %d",
            self.__class__.__name__, os.getpid())

        # Register SIGINT handler which will exit service process
        def sigint_handler(unused_signum, unused_frame):
            """
            Exit service process when SIGINT is reached.
            """
            self.stop()
        signal.signal(signal.SIGINT, sigint_handler)

        # Initialize logging
        self.context.config.configure_logging()
        # Initialize child
        self.context.initialize_child(SERVICE_PROCESS, process=self)

        next_loop_time = 0
        while 1:
            # Exit if pid of the parent process has changed (parent process
            # has exited and init is new parent) or if stop flag is set.
            if os.getppid() != self._parent_pid or self._stop_event.is_set():
                break
            # Repeatedly call loop method. After first call set ready flag.
            if time.time() >= next_loop_time:
                try:
                    self.loop()
                except Exception:
                    self.logger.exception(
                        "Worker '%s' failed", self.__class__.__name__)
                else:
                    if not next_loop_time and not self.ready:
                        self._ready.value = True
                next_loop_time = time.time() + self.interval
            else:
                time.sleep(0.25)
533403
def sigusr2_handler(self, unused_signum, unused_frame):
        
        if self._sigusr1_handler_func is not None:
            self._sigusr2_handler_func(self.context)
1033813
def signal_handler(self, signum, frame):
        
        self.print_exit()
        print("\n(Terminated with signal %d)\n" % (signum))
        sys.exit(0)
971136
def _handle_signal_gracefully(cls, signum, signame, traceback_lines):
    """"""
    # Extract the stack, and format an entry to be written to the exception log.
    formatted_traceback = cls._format_traceback(traceback_lines=traceback_lines,
                                                should_print_backtrace=True)
    signal_error_log_entry = cls._CATCHABLE_SIGNAL_ERROR_LOG_FORMAT.format(
      signum=signum,
      signame=signame,
      formatted_traceback=formatted_traceback)
    # TODO: determine the appropriate signal-safe behavior here (to avoid writing to our file
    # descriptors re-entrantly, which raises an IOError).
    # This method catches any exceptions raised within it.
    cls.log_exception(signal_error_log_entry)

    # Create a potentially-abbreviated traceback for the terminal or other interactive stream.
    formatted_traceback_for_terminal = cls._format_traceback(
      traceback_lines=traceback_lines,
      should_print_backtrace=cls._should_print_backtrace_to_terminal)
    terminal_log_entry = cls._CATCHABLE_SIGNAL_ERROR_LOG_FORMAT.format(
      signum=signum,
      signame=signame,
      formatted_traceback=formatted_traceback_for_terminal)
    # Exit, printing the output to the terminal.
    cls._exit_with_failure(terminal_log_entry)
179646
def run(self):
    """"""
    # Prevent the KeyboardInterrupt being raised inside the process.
    # This will prevent a process from generating a traceback when interrupted.
    signal.signal(signal.SIGINT, signal.SIG_IGN)

    # A SIGTERM signal handler is necessary to make sure IPC is cleaned up
    # correctly on terminate.
    signal.signal(signal.SIGTERM, self._SigTermHandler)

    # A SIGSEGV signal handler is necessary to try to indicate where
    # worker failed.
    # WARNING the SIGSEGV handler will deadlock the process on a real segfault.
    if self._enable_sigsegv_handler:
      self._original_sigsegv_handler = signal.signal(
          signal.SIGSEGV, self._SigSegvHandler)

    self._pid = os.getpid()
    self._process_information = process_info.ProcessInfo(self._pid)

    # We need to set the is running status explicitly to True in case
    # the process completes before the engine is able to determine
    # the status of the process, e.g. in the unit tests.
    self._status_is_running = True

    # Logging needs to be configured before the first output otherwise we
    # mess up the logging of the parent process.
    loggers.ConfigureLogging(
        debug_output=self._debug_output, filename=self._log_filename,
        quiet_mode=self._quiet_mode)

    logger.debug(
        'Process: {0!s} (PID: {1:d}) started'.format(self._name, self._pid))

    self._StartProcessStatusRPCServer()

    self._Main()

    self._StopProcessStatusRPCServer()

    logger.debug(
        'Process: {0!s} (PID: {1:d}) stopped'.format(self._name, self._pid))

    # Make sure log files are cleanly closed.
    logging.shutdown()

    self._status_is_running = False
668908
def stop(self):
        

        if self.original_handler is not None:
            signal.signal(signal.SIGWINCH, self.original_handler)
649774
def _signal_handler(self, *_) -> None:
        
        if self._num_signals == 0:
            logging.warning('Interrupt signal caught - training will be terminated')
            logging.warning('Another interrupt signal will terminate the program immediately')
            self._num_signals += 1
        else:
            logging.error('Another interrupt signal caught - terminating program immediately')
            sys.exit(2)