def test_sigwaitinfo(self):
        # Issue #25277: The sleep is a weak synchronization between the parent
        # and the child process. If the sleep is too low, the test hangs on
        # slow or highly loaded systems.
        self.sleep_time = 2.0

        signum = signal.SIGUSR1
        pid = os.getpid()

        old_handler = signal.signal(signum, lambda *args: None)
        self.addCleanup(signal.signal, signum, old_handler)

        code = '\n'.join((
            'import os, time',
            'pid = %s' % os.getpid(),
            'signum = %s' % int(signum),
            'sleep_time = %r' % self.sleep_time,
            'time.sleep(sleep_time)',
            'os.kill(pid, signum)',
        ))

        t0 = time.monotonic()
        proc = self.subprocess(code)
        with kill_on_error(proc):
            # parent
            signal.sigwaitinfo([signum])
            dt = time.monotonic() - t0
            self.assertEqual(proc.wait(), 0)

        self.assertGreaterEqual(dt, self.sleep_time)
Ejemplo n.º 2
0
    def test_sigwaitinfo(self):
        signum = signal.SIGUSR1
        pid = os.getpid()

        old_handler = signal.signal(signum, lambda *args: None)
        self.addCleanup(signal.signal, signum, old_handler)

        code = '\n'.join((
            'import os, time',
            'pid = %s' % os.getpid(),
            'signum = %s' % int(signum),
            'sleep_time = %r' % self.sleep_time,
            'time.sleep(sleep_time)',
            'os.kill(pid, signum)',
        ))

        t0 = time.monotonic()
        proc = self.subprocess(code)
        with kill_on_error(proc):
            # parent
            signal.sigwaitinfo([signum])
            dt = time.monotonic() - t0
            self.assertEqual(proc.wait(), 0)

        self.assertGreaterEqual(dt, self.sleep_time)
Ejemplo n.º 3
0
    def test_sigwaitinfo(self):
        # Issue #25277: The sleep is a weak synchronization between the parent
        # and the child process. If the sleep is too low, the test hangs on
        # slow or highly loaded systems.
        self.sleep_time = 2.0

        signum = signal.SIGUSR1
        pid = os.getpid()

        old_handler = signal.signal(signum, lambda *args: None)
        self.addCleanup(signal.signal, signum, old_handler)

        code = '\n'.join((
            'import os, time',
            'pid = %s' % os.getpid(),
            'signum = %s' % int(signum),
            'sleep_time = %r' % self.sleep_time,
            'time.sleep(sleep_time)',
            'os.kill(pid, signum)',
        ))

        t0 = time.monotonic()
        proc = self.subprocess(code)
        with kill_on_error(proc):
            # parent
            signal.sigwaitinfo([signum])
            dt = time.monotonic() - t0
            self.assertEqual(proc.wait(), 0)

        self.assertGreaterEqual(dt, self.sleep_time)
Ejemplo n.º 4
0
def main(args, gdrive_client):
    bind_addr = to_addr(args.bind)
    transcoder_addr = to_addr(args.transcoder)
    devwatch_addr = to_addr(args.devwatch)

    daemon = JobQueueDaemon(["q_import", "q_upload"])
    daemon.active_imports = {}
    daemon.active_transcodes = {}
    daemon.add_executor("q_import", ImportExecutor, args.output_dir,
                        transcoder_addr, daemon)
    daemon.add_executor("q_upload", UploadExecutor, gdrive_client,
                        args.gdrive_root, args.output_dir, devwatch_addr,
                        daemon)
    daemon.add_server(socketserver.TCPServer(bind_addr, ImportRequestHandler))

    daemon.start()
    logging.info("Started")
    try:
        sig = signal.sigwaitinfo({signal.SIGINT})  # TODO handle sigterm
    except KeyboardInterrupt:
        sig = signal.SIGINT
    finally:
        sig = signal.Signals(sig.si_signo)
        logging.info("Shutting down after %s", sig.name)
        daemon.shutdown()
Ejemplo n.º 5
0
def main(args):
    bind_addr = to_addr(args.bind)
    importer_addr = to_addr(args.importer)
    # TODO check mount privilege

    daemon = JobQueueDaemon(["q_import"])
    udev_context = pyudev.Context()
    daemon.add_executor(None,
                        DevwatchExecutor,
                        udev_context,
                        daemon,
                        daemon.job_queues["q_import"],
                        udev_filter="block",
                        event_filter=check_match)
    daemon.add_executor("q_import", ImportExecutor, importer_addr)
    daemon.add_server(socketserver.TCPServer(bind_addr,
                                             DevwatchRequestHandler))

    daemon.start()
    logging.info("Started")
    try:
        sig = signal.sigwaitinfo({signal.SIGINT})  # TODO handle sigterm
    except KeyboardInterrupt:
        sig = signal.SIGINT
    finally:
        sig = signal.Signals(sig.si_signo)
        logging.info("Shutting down after %s", sig.name)
        daemon.shutdown()
Ejemplo n.º 6
0
    def test_sigwaitinfo(self):
        # Issue #25277, #25868: give a few miliseconds to the parent process
        # between os.write() and signal.sigwaitinfo() to works around a race
        # condition
        self.sleep_time = 0.100

        signum = signal.SIGUSR1
        pid = os.getpid()

        old_handler = signal.signal(signum, lambda *args: None)
        self.addCleanup(signal.signal, signum, old_handler)

        rpipe, wpipe = os.pipe()

        code = '\n'.join((
            'import os, time',
            'pid = %s' % os.getpid(),
            'signum = %s' % int(signum),
            'sleep_time = %r' % self.sleep_time,
            'rpipe = %r' % rpipe,
            'os.read(rpipe, 1)',
            'os.close(rpipe)',
            'time.sleep(sleep_time)',
            'os.kill(pid, signum)',
        ))

        t0 = time.monotonic()
        proc = self.subprocess(code, pass_fds=(rpipe, ))
        os.close(rpipe)
        with kill_on_error(proc):
            # sync child-parent
            os.write(wpipe, b'x')
            os.close(wpipe)

            # parent
            signal.sigwaitinfo([signum])
            dt = time.monotonic() - t0
            self.assertEqual(proc.wait(), 0)

        self.assertGreaterEqual(dt, self.sleep_time)
Ejemplo n.º 7
0
    def test_sigwaitinfo(self):
        # Issue #25277, #25868: give a few milliseconds to the parent process
        # between os.write() and signal.sigwaitinfo() to works around a race
        # condition
        self.sleep_time = 0.100

        signum = signal.SIGUSR1
        pid = os.getpid()

        old_handler = signal.signal(signum, lambda *args: None)
        self.addCleanup(signal.signal, signum, old_handler)

        rpipe, wpipe = os.pipe()

        code = '\n'.join((
            'import os, time',
            'pid = %s' % os.getpid(),
            'signum = %s' % int(signum),
            'sleep_time = %r' % self.sleep_time,
            'rpipe = %r' % rpipe,
            'os.read(rpipe, 1)',
            'os.close(rpipe)',
            'time.sleep(sleep_time)',
            'os.kill(pid, signum)',
        ))

        t0 = time.monotonic()
        proc = self.subprocess(code, pass_fds=(rpipe,))
        os.close(rpipe)
        with kill_on_error(proc):
            # sync child-parent
            os.write(wpipe, b'x')
            os.close(wpipe)

            # parent
            signal.sigwaitinfo([signum])
            dt = time.monotonic() - t0
            self.assertEqual(proc.wait(), 0)

        self.assertGreaterEqual(dt, self.sleep_time)
Ejemplo n.º 8
0
    def test_sigwaitinfo(self):
        signum = signal.SIGUSR1
        pid = os.getpid()

        old_handler = signal.signal(signum, lambda *args: None)
        self.addCleanup(signal.signal, signum, old_handler)

        t0 = time.monotonic()
        child_pid = os.fork()
        if child_pid == 0:
            # child
            try:
                self._sleep()
                os.kill(pid, signum)
            finally:
                os._exit(0)
        else:
            # parent
            signal.sigwaitinfo([signum])
            dt = time.monotonic() - t0
            os.waitpid(child_pid, 0)

        self.assertGreaterEqual(dt, self.sleep_time)
Ejemplo n.º 9
0
def main():
    # Check python version
    if (sys.version_info[0] < 3):
        log("You are trying to use Python version {}.{}.{}".format(
            sys.version_info[0], sys.version_info[1], sys.version_info[2]))
        log("ANT requires Python 3.0+.")
        return

    # Check if this is root user
    thisUid = os.getuid()
    if thisUid != 0:
        log("You(uid={}) are not root user. Please try it again on root.".
            format(thisUid))
        return

    # Parse option arguments
    parser = argparse.ArgumentParser(description="ANT options.")
    parser.add_argument("--debug-appcore",
                        "-dac",
                        dest="debugappcore",
                        action="store_true",
                        help="Debug Appcore Manager")
    parser.add_argument("--debug-apps",
                        "-da",
                        dest="debugapps",
                        action="store_true",
                        help="Debug Apps")
    args = parser.parse_args()

    # Register signal handlers
    signal.signal(signal.SIGCHLD, signal_handler)
    signal.signal(signal.SIGINT, signal_handler)

    # Initialize Completed
    log("args: {}".format(args))
    on_did_initialize(args)

    # Wait for signals
    while True:
        siginfo = signal.sigwaitinfo({signal.SIGCHLD, signal.SIGINT})
        if siginfo.si_signo == signal.SIGCHLD:
            # Child daemon process is dead
            on_did_dead_deamon(siginfo.si_pid)
        elif siginfo.si_signo == signal.SIGINT:
            # Halt ANT triggered by user
            on_did_halt_by_user()
            return
Ejemplo n.º 10
0
def main(args):
    bind_addr = to_addr(args.bind)
    importer_addr = to_addr(args.importer)

    daemon = JobQueueDaemon(["q_transcode_accept", "q_transcode_finished"])
    report_queue = daemon.job_queues["q_transcode_finished"]
    daemon.add_executor("q_transcode_accept", TranscodeExecutor, report_queue)
    daemon.add_executor("q_transcode_finished", ResultReporter, importer_addr)
    daemon.add_server(
        socketserver.TCPServer(bind_addr, TranscodeRequestHandler))

    daemon.start()
    logging.info("Started")
    try:
        sig = signal.sigwaitinfo({signal.SIGINT})  # TODO handle sigterm
    except KeyboardInterrupt:
        sig = signal.SIGINT
    finally:
        sig = signal.Signals(sig.si_signo)
        logging.info("Shutting down after %s", sig.name)
        daemon.shutdown()
#!/usr/bin/python3
import os
import signal

# signal id -> signal name
SIGNALS_TO_NAMES_DICT = dict((getattr(signal, n), n) \
    for n in dir(signal) if n.startswith('SIG') and '_' not in n )

print("My PID is %d, you can stop me with SIGUSR1" % os.getpid())

while True:
    info = signal.sigwaitinfo(range(1, signal.NSIG))

    if info.si_signo == signal.SIGUSR1:
        print("Received deadly signal %r" % (SIGNALS_TO_NAMES_DICT[info.si_signo]))
        break
    else:
        print("Received signal %r" % (SIGNALS_TO_NAMES_DICT[info.si_signo]))

Ejemplo n.º 12
0
 def wait_func(signum):
     signal.sigwaitinfo([signum])
import signal, sys
from time import sleep


def terminated(signum, frame):
    pass


signal.signal(signal.SIGTERM, terminated)
signal.signal(signal.SIGINT, terminated)
while True:
    siginfo = signal.sigwaitinfo({signal.SIGINT, signal.SIGTERM})
    with open("terminated.txt", "w") as f:
        f.write("Process terminated by %d\n" % siginfo.si_pid)
    sys.exit(0)
Ejemplo n.º 14
0
            print(f'Updated {self.__pid_file} to {os.getpid()}')

if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='Subscription service for Alt+Shift language switch')
    parser.add_argument('--pid-file', '-p', type=pathlib.Path, default=pathlib.Path('/var/run/alt-shift-notify/service.pid'))
    parser.add_argument('--verbose', dest='verbose', action='store_true')
    args = parser.parse_args()
    if not args.pid_file.is_absolute():
        args.pid_file = pathlib.Path(pathlib.Path.cwd(), args.pid_file)
    pid_file = args.pid_file
    if args.verbose:
        is_verbose = True
    context = pyudev.Context()
    manager = KeyboardThreadManager(context)
    threading.current_thread().name = 'SubscriberThread'
    signal.pthread_sigmask(signal.SIG_BLOCK, [signal.SIGUSR1, signal.SIGUSR2])
    pid_file_creator = PIDFileCreator(pid_file=pid_file)
    pid_file_creator.start()
    while True:
        received = signal.sigwaitinfo([signal.SIGUSR1, signal.SIGUSR2, signal.SIGINT, signal.SIGTERM])
        if received.si_signo == signal.SIGUSR1:
            if is_verbose:
                print(f'Adding subscriber: {received.si_pid}')
            subscriber_list.add(received.si_pid)
        elif received.si_signo == signal.SIGUSR2:
            if is_verbose:
                print(f'Removing subscriber: {received.si_pid}')
            subscriber_list.remove(received.si_pid)
        elif received.si_signo == signal.SIGTERM or received.si_signo == signal.SIGINT:
            sys.exit(0)
Ejemplo n.º 15
0
                config['Node']['Nodes'][
                    f'node_{j1}'] = f'https://go.tvbit.local:82{j1}6'
        with open(f'config_{j}.json', 'w') as f:
            json.dump(config, f)
        servers.append(create_server(f'out-{j}.log', f'config_{j}.json', j))
else:
    servers.append(create_server('out.log', args.config, 0))
print('servers', servers)

t = threading.Thread(target=read_commands, args=(servers, ), daemon=True)
t.start()

signal.signal(signal.SIGUSR1, signal_handler)
ready = set()
while True:
    try:
        siginfo = signal.sigwaitinfo([signal.SIGUSR1])
        print('signal received', siginfo)
        for s in servers:
            if s[0] == siginfo.si_pid:
                ready.add(siginfo.si_pid)
        if len(ready) == len(servers):
            print('all servers ready')
            for s in servers:
                s[1].put('proceed')
    except KeyboardInterrupt:
        for s in servers:
            s[1].put('stop')
            s[1].join()
        break
Ejemplo n.º 16
0
 def wait_func(signum):
     signal.sigwaitinfo([signum])
Ejemplo n.º 17
0
#!/usr/local/Caskroom/miniconda/base/envs/cybersecurity/bin/python

import signal, sys
from time import sleep


def terminated(signum, frame):
    pass


#catching any commands throwing SIGTERM, SIGINT, kill etc
#if a process attemted to kill this process we can log what sent the signal
#SIGKILL is an uncatchable signal (will not work with this)
signal.signal(signal.SIGTERM, terminated)
signal.signal(signal.SIGINT, terminated)

while True:
    #only availabe on UNIX (signal.sigwait)
    siginfo = signal.sigwaitinfo((signal.SIGINT, signal.SIGTERM))
    with open("terminated.txt", "w") as f:
        f.write(f"Process terminated by {siginfo.si_pid}\n")
    sys.exit(0)
Ejemplo n.º 18
0
    def run(self, wanted_interfaces, log_filename_by_process=None):
        """fork processes for each wanted interface

        This function returns for the child processes (i.e.: they may continue using stdin/stdout).
        The parent process (the interface manager) stays alive and never returns.
        """
        if not self.run_and_stop_interfaces(
                wanted_interfaces,
                log_filename_by_process=log_filename_by_process):
            # we are a managed interface process - simply return
            return
        # we are the manager
        # Ignore all signals that we want to listen for, but store their previous handlers.
        original_signal_handlers = {}
        for one_signal in {
                signal.SIGUSR1,
                signal.SIGHUP,
                signal.SIGTERM,
                signal.SIGCHLD,
        }:
            # The signal handler signal.SIG_IGN is not appropriate: it would prevent "sigwaitinfo"
            # below from capturing these signals.
            original_signal_handlers[one_signal] = signal.signal(
                one_signal, lambda *args: None)
        should_finish = False
        while not should_finish:
            try:
                signal_info = signal.sigwaitinfo(set(original_signal_handlers))
            except KeyboardInterrupt:
                self.logger.info("Received CTRL-C")
                should_finish = True
                continue
            if signal_info.si_signo == signal.SIGTERM:
                self.logger.info("Received termination signal")
                should_finish = True
            elif signal_info.si_signo == signal.SIGCHLD:
                # a child process signals its termination
                matched_specs = {
                    spec
                    for spec, pid in self.running_interface_processes.items()
                    if pid == signal_info.si_pid
                }
                for spec in matched_specs:
                    self.logger.info(
                        "A child signals its termination: %d %s",
                        signal_info.si_pid,
                        spec,
                    )
                    self.running_interface_processes.pop(spec)
                    # in any case: retrieve its result (otherwise it will end up as a zombie)
                    os.waitpid(signal_info.si_pid, os.WNOHANG)
                if not self.running_interface_processes:
                    self.logger.info(
                        "All child processes are gone. Going home, too.")
                    should_finish = True
            elif signal_info.si_signo == signal.SIGUSR1:
                # print all currently running processes
                for spec, pid in self.running_interface_processes.items():
                    print("{:d}\t{}".format(pid, spec))
            elif signal_info.si_signo == signal.SIGHUP:
                # Parse the wanted set of interfaces from a given text file and update the list of
                # running processes appropriately.
                raise NotImplementedError(
                    "The 'update interfaces from file' feature is not supported, yet."
                )
            else:
                raise NotImplementedError("Received unknown signal")
        # kill all child processes
        self.run_and_stop_interfaces(set())
        sys.exit(0)