def test_sigtimedwait(self): t0 = time.monotonic() signal.sigtimedwait([signal.SIGUSR1], self.sleep_time) dt = time.monotonic() - t0 if sys.platform.startswith('aix'): # On AIX, sigtimedwait(0.2) sleeps 199.8 ms self.assertGreaterEqual(dt, self.sleep_time * 0.9) else: self.assertGreaterEqual(dt, self.sleep_time)
def run_mock_server(*args, wait=10): """ :rtype: Process """ mock_server_process = None testargs = [PROGRAM, *args] with patch.object(sys, 'argv', testargs): mock_server_process = Process(target=initiate, args=()) mock_server_process.start() signal.signal(signal.SIGALRM, signal_handler) signal.sigtimedwait([signal.SIGALRM], wait) return mock_server_process
def wait(self, timeout=None): success = False if timeout is None: signal.sigwait({ self._signalnum, }) success = True else: success = (signal.sigtimedwait({ self._signalnum, }, timeout) is not None) self._occured = success return success
def main(args=None): if args is None: args = sys.argv[1:] parser = argparse.ArgumentParser() parser.add_argument("-a", "--aliasFile", action="store", default=os.environ["HOME"] + "/.cloudmra/alias.json", help="Filesystem path to alias json file.") parser.add_argument("-c", "--configFile", action="store", default=os.environ["HOME"] + "/.cloudmra/cloudmra.config", help="Filesystem path to config json file.") parser.add_argument( "-S", "--systemd", action="store_true", help="Run as a systemd service." ) # store_true is false by default, and returns True when flag is set. arguments = parser.parse_args() with open(arguments.aliasFile, 'r') as aliasjson: ALIAS = (aliasjson.read()) with open(arguments.configFile, 'r') as configjson: CONFIG = json.loads(configjson.read()) main_overseer = overseer(CONFIG, ALIAS, LOOP=arguments.systemd) signal.signal(signalnum=signal.SIGTERM, handler=main_overseer.signal_handler) signal.signal(signalnum=signal.SIGINT, handler=main_overseer.signal_handler) if main_overseer.CONTINUE is False: main_overseer.process() else: while main_overseer.CONTINUE: main_overseer.process() if signal.sigtimedwait(set([signal.SIGTERM, signal.SIGINT]), main_overseer.SLEEP_TIME): main_overseer.signal_handler(signal.SIGTERM) return 0
def handle(self, **options): pidfile_path = os.path.join(os.environ.get("BUILDDIR", "."), ".runbuilds.pid") with open(pidfile_path, 'w') as pidfile: pidfile.write("%s" % os.getpid()) # Clean up any stale/failed builds from previous Toaster run self.runbuild() signal.signal(signal.SIGUSR1, lambda sig, frame: None) while True: sigset = signal.sigtimedwait([signal.SIGUSR1], 5) if sigset: for sig in sigset: # Consume each captured pending event self.runbuild() else: # Check for build exceptions self.check_dead_builds()
def inner(): # Block signals unconditionally to avoid them impacting our return # code. signal.pthread_sigmask(signal.SIG_SETMASK, test_signals) for sig in test_signals: os.kill(pid, sig) received_signal = False received_signals = signal.sigpending() while received_signals != test_signals: result = signal.sigtimedwait(forwarded_signals, 0.1) if result is not None: received_signal = True received_signals.add(result.si_signo) elif received_signal: # Only trace after the first empty response. received_signal = False logger.debug("Waiting for %s", test_signals - received_signals) output_path.write_text(to_string(received_signals), encoding="utf-8")
def launch(self): self.check() received = False def set_received(*_): nonlocal received received = True signal.signal(signal.SIGUSR1, set_received) pid = self.fork_zeo() if not received: while not signal.sigtimedwait([signal.SIGUSR1], 1): pid, waitres = os.waitpid(pid, os.WNOHANG) if pid: log.error( 'Database server failed to start (check log above).') sys.exit(1) settings.DB_URI = urlunsplit(('zeo', '', self.zeo_path, '', '')) log.debug('Launched built-in ZEO') return pid
def main() -> None: """Run the main processing loop for the certmgr instance.""" mode_choices: Dict[str, BaseCert] = { "self-signed": SelfSignedCert(), "letsencrypt": LetsEncryptCert(), "cert-server": CertProxyServer(), "cert-client": CertProxyClient(), } cert_store = get_setting("CERT_STORE") for subdir in ("nginx", "selfsigned"): os.makedirs(f"{cert_store}/{subdir}", 0o755, True) cert_mode = get_setting("CERT_MODE") print(f"Running in {cert_mode} mode") cert_obj = mode_choices.get(cert_mode, None) if cert_obj is not None: cert_obj.create() # The certmgr will respond to the SIGUSR1 signal by checking for certificate # renewal ahead of the scheduled time. The initial use for this is to # allow the NUC to trigger the certmgr (running in "cert-client" mode) to # check for an updated certificate when it detects that the wired ethernet # connection is up. usr1_signal = signal.SIGUSR1 signal.signal(usr1_signal, handle_user_sig1) while True: # check for renewal after 12 hours or SIGUSR1 received got_sig = signal.sigtimedwait([usr1_signal], 12 * 3600) # (12 hrs x 3600 sec/hr) if got_sig is not None: print(f"Renew triggered by signal ({got_sig.si_signo}).") cert_obj.renew() else: print(f"Cannot run {cert_mode} mode") sys.exit(1)
def test_sigtimedwait(self): t0 = time.monotonic() signal.sigtimedwait([signal.SIGUSR1], self.sleep_time) dt = time.monotonic() - t0 self.assertGreaterEqual(dt, self.sleep_time)
web_proc.start() # print('seedling: web process started, daemon: %s' % web_proc.daemon) def signal_handler(sig, context): global exit_flag if sig == signal.SIGTERM: exit_flag = True signal.signal(signal.SIGTERM, signal_handler) exit_flag = False while not exit_flag: siginfo = signal.sigtimedwait([signal.SIGTERM], 5) if not control_proc.is_alive() or not web_proc.is_alive(): exit_flag = True elif siginfo and siginfo.si_signo == signal.SIGTERM: exit_flag = True if web_proc.is_alive(): print('seedling: terminate web') os.kill(web_proc.pid, signal.SIGTERM) if control_proc.is_alive(): print('seedling: terminate control') clear_queue(msg_queue) msg_queue.put('end') # Give control loop time to update instrumentation
def wrapper(*args): # print(func.__name__, end='') args[0].private_queue.put(os.getpid()) signal.sigtimedwait([signal.SIGUSR1], 1.5) # print(func.__name__, "end") return func(*args)
def wait_func(signum): signal.sigtimedwait([signum], 120.0)
database = config['database']['connection'] sensors = gather_sensors(config) xs1_host = config['xs1']['host'] update_interval = int(config['updater']['interval']) db_connection = DatabaseConnection(database, sensors) while True: xs1_connection = XS1Connection(xs1_host) sensor_names = db_connection.get_sensors() sensor_values = list() for sensor_name in sensor_names: sensor = xs1_connection.get_sensor_by_name(sensor_name) if sensor: sensor.update(xs1_connection) sensor_values.append(sensor.value) else: raise RuntimeError('Sensor "'+sensor_name+'" does not exist.') xs1_connection.close() db_connection.insert_measurements(sensor_values) db_connection.commit() if signal.sigtimedwait([signal.SIGABRT, signal.SIGINT, signal.SIGTERM], update_interval) != None: break db_connection.close()
def sleep(self, seconds): """Sleep for a certain amount of seconds. """ ret = signal.sigtimedwait(SIGNALS, seconds) if ret is not None: return ret.si_signo
current_time = 0.0 diffs = [] infrared = Button(0, pull_up=False) def infra_event_pressed(): global current_time current_time = time.time() def infra_event_released(): global diffs diff_time = time.time() - current_time diffs += [diff_time] # print("Infrared Deactivated", diff_time * 1000000, "uS") infrared.when_pressed = infra_event_pressed infrared.when_released = infra_event_released sigtimedwait([], 5) print([int(a * 10**6) for a in diffs]) # state = 0 # while True: # if infrared.value != state: # temp_time = time.time() # diff = temp_time - current_time1 # current_time1 = temp_time # print("difference ", diff * 1000000) # state = infrared.value
def wrapper(*args): # print("start wait...", end='') args[0].public_queue.put(os.getpid()) signal.sigtimedwait([signal.SIGUSR1], 1.5) # print("end") return func(*args)