for i in [x for x in dir(signal) if x.startswith("SIG")]:
		try:
			signum = getattr(signal,i)
			print("register {}, {}".format(signum, i))
			signal.signal(signum, handler)
		except:
			print("Skipping %s"%i)
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()
168158
def sigint_handler(signum, frame):
    """"""
    global _handled_int
    if not _handled_int:
        _handled_int = True
        if not _env_var_true("_REZ_QUIET_ON_SIG"):
            print >> sys.stderr, "Interrupted by user"
        sigbase_handler(signum, frame)
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) )
1255386
public int signal(int signal, String arg)
	throws GramException, GSSException {
	return Gram.jobSignal(this, signal, arg);
    }
513589
def exception_to_signal(sig: Union[SignalException, signal.Signals]):
    
    if isinstance(sig, SignalException):
        signum = sig.signum
    else:
        signum = sig.value
    signal.signal(signum, signal.SIG_DFL)
533403
def sigusr2_handler(self, unused_signum, unused_frame):
        
        if self._sigusr1_handler_func is not None:
            self._sigusr2_handler_func(self.context)
1208802
def signal(signal=None):
    '''
    
    '''
    valid_signals = ('start', 'reopen', 'stop', 'quit', 'reload')

    if signal not in valid_signals:
        return

    # Make sure you use the right arguments
    if signal == "start":
        arguments = ''
    else:
        arguments = ' -s {0}'.format(signal)
    cmd = __detect_os() + arguments
    out = __salt__['cmd.run_all'](cmd)

    # A non-zero return code means fail
    if out['retcode'] and out['stderr']:
        ret = out['stderr'].strip()
    # 'nginxctl configtest' returns 'Syntax OK' to stderr
    elif out['stderr']:
        ret = out['stderr'].strip()
    elif out['stdout']:
        ret = out['stdout'].strip()
    # No output for something like: nginxctl graceful
    else:
        ret = 'Command: "{0}" completed successfully!'.format(cmd)
    return ret
799331
def enable_sig_handler(signal_name, handler):
    '''
    
    '''
    if hasattr(signal, signal_name):
        signal.signal(getattr(signal, signal_name), handler)
1229561
public synchronized void registerSignal(int signalNumber, Runnable callback, boolean replace) {
        String signalName = signalMap.get(signalNumber);
        if (signalName == null) {
            LOG.warn("Invalid signalNumber " + signalNumber);
            return;
        }

        LOG.info("Begin to register signal of {}", signalName);
        try {
            SignalHandler oldHandler = Signal.handle(new Signal(signalName), this);
            LOG.info("Successfully register {} handler", signalName);

            Runnable old = signalHandlers.put(signalNumber, callback);
            if (old != null) {
                if (!replace) {
                    oldSignalHandlers.put(signalNumber, oldHandler);

                } else {
                    LOG.info("Successfully old {} handler will be replaced", signalName);
                }

            }
            LOG.info("Successfully register signal of {}", signalName);
        } catch (Exception e) {
            LOG.error("Failed to register " + signalName + ":" + signalNumber + ", Signal already used by VM or OS: SIGILL");
        }

    }
1085026
def register_signal_handlers
      trap('TERM') { shutdown! }
      trap('INT')  { shutdown! }

      begin
        trap('QUIT') { shutdown }
      rescue ArgumentError
        warn "Signals TERM and/or QUIT not supported."
      end

      log! "Registered signals"
    end
810954
def _generic_signal_handler(self, signal_type):
        
        print("</pre>")
        message = "Got " + signal_type + ". Failing gracefully..."
        self.timestamp(message)
        self.fail_pipeline(KeyboardInterrupt(signal_type), dynamic_recover=True)
        sys.exit(1)
1238209
def init_logging(verbose=False, format='%(asctime)s %(message)s'):
    
    def sig_handler(signum, frame):
        logger = logging.getLogger()
        log_level = logger.level
        if log_level == logging.DEBUG:
            log_level = logging.WARN
        else:
            log_level = logging.DEBUG
        logging.warn('Got signal %d, setting log level to %d',
                     signum, log_level)
        logger.setLevel(log_level)

    signal.signal(signal.SIGUSR1, sig_handler)

    if verbose:
        initial_level = logging.DEBUG
    else:
        initial_level = logging.WARN
    logging.getLogger().setLevel(initial_level)
    logging.basicConfig(format=format, level=initial_level)
979089
def set_signal_handler(self, sigs=None):
        
        if sigs is None:
            sigs = (signal.SIGTERM, signal.SIGINT, signal.SIGUSR1, signal.SIGUSR2, signal.SIGHUP)

        func = self.manage_signal
        if os.name == "nt":  # pragma: no cover, no Windows implementation currently
            try:
                import win32api
                win32api.SetConsoleCtrlHandler(func, True)
            except ImportError:
                version = ".".join([str(i) for i in os.sys.version_info[:2]])
                raise Exception("pywin32 not installed for Python " + version)
        else:
            for sig in sigs:
                signal.signal(sig, func)
609919
def read_block(handle, signal):
    
    signal_len = len(signal)
    it = (x[1] for x in groupby(handle,
        key=lambda row: row.strip()[:signal_len] == signal))
    found_signal = False
    for header in it:
        header = list(header)
        for h in header[:-1]:
            h = h.strip()
            if h[:signal_len] != signal:
                continue
            yield h, []  # Header only, no contents
        header = header[-1].strip()
        if header[:signal_len] != signal:
            continue
        found_signal = True
        seq = list(s.strip() for s in next(it))
        yield header, seq

    if not found_signal:
        handle.seek(0)
        seq = list(s.strip() for s in handle)
        yield None, seq
856942
def sigusr1_handler(self, unused_signum, unused_frame):
        
        if self._sigusr1_handler_func is not None:
            self._sigusr1_handler_func(self.context)
247459
def _register_signal_handler(self, description, signal, handler):
        
        from flask import signals

        if not signals.signals_available:
            self.app.logger.warn('blinker needs to be installed in order to support %s'.format(description))
        self.app.logger.info('Enabling {}'.format(description))
        # Weak references won't work if handlers are methods rather than functions.
        signal.connect(handler, sender=self.app, weak=False)
382112
def check(self, order, sids):
        '''  '''
        payload = "{}"
        #TODO store hashes {'intuition': {'id1': value, 'id2': value}}
        # Block self.timeout seconds on self.channel for a message
        raw_msg = self.client.blpop(self.channel, timeout=self.timeout)
        if raw_msg:
            _, payload = raw_msg

            msg = json.loads(payload.replace("'", '"'), encoding='utf-8')
            for sid in msg.keys():
                #TODO Harmonize lower() and upper() symbols
                if sid.lower() in map(str.lower, sids):
                    print('ordering {} of {}'.format(msg[sid], sid))
                    #order(sid.upper(), msg[sid])
                    order(sid, msg[sid])
                else:
                    print('skipping unknown symbol {}'.format(sid))