Python os.getppid() Examples

The following are 30 code examples of os.getppid(). 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 also want to check out all available functions/classes of the module os , or try the search function .
Example #1
Source File: processes.py    From tf-pose with Apache License 2.0 7 votes vote down vote up
def startEventLoop(name, port, authkey, ppid, debug=False):
    if debug:
        import os
        cprint.cout(debug, '[%d] connecting to server at port localhost:%d, authkey=%s..\n' 
                    % (os.getpid(), port, repr(authkey)), -1)
    conn = multiprocessing.connection.Client(('localhost', int(port)), authkey=authkey)
    if debug:
        cprint.cout(debug, '[%d] connected; starting remote proxy.\n' % os.getpid(), -1)
    global HANDLER
    #ppid = 0 if not hasattr(os, 'getppid') else os.getppid()
    HANDLER = RemoteEventHandler(conn, name, ppid, debug=debug)
    while True:
        try:
            HANDLER.processRequests()  # exception raised when the loop should exit
            time.sleep(0.01)
        except ClosedError:
            HANDLER.debugMsg('Exiting server loop.')
            sys.exit(0) 
Example #2
Source File: test_process.py    From vnpy_crypto with MIT License 7 votes vote down vote up
def test_ppid(self):
        if hasattr(os, 'getppid'):
            self.assertEqual(psutil.Process().ppid(), os.getppid())
        this_parent = os.getpid()
        sproc = get_test_subprocess()
        p = psutil.Process(sproc.pid)
        self.assertEqual(p.ppid(), this_parent)
        # no other process is supposed to have us as parent
        reap_children(recursive=True)
        if APPVEYOR:
            # Occasional failures, see:
            # https://ci.appveyor.com/project/giampaolo/psutil/build/
            #     job/0hs623nenj7w4m33
            return
        for p in psutil.process_iter():
            if p.pid == sproc.pid:
                continue
            # XXX: sometimes this fails on Windows; not sure why.
            self.assertNotEqual(p.ppid(), this_parent, msg=p) 
Example #3
Source File: worker.py    From sanic with MIT License 6 votes vote down vote up
def _check_alive(self):
        # If our parent changed then we shut down.
        pid = os.getpid()
        try:
            while self.alive:
                self.notify()

                req_count = sum(
                    self.servers[srv]["requests_count"] for srv in self.servers
                )
                if self.max_requests and req_count > self.max_requests:
                    self.alive = False
                    self.log.info(
                        "Max requests exceeded, shutting down: %s", self
                    )
                elif pid == os.getpid() and self.ppid != os.getppid():
                    self.alive = False
                    self.log.info("Parent changed, shutting down: %s", self)
                else:
                    await asyncio.sleep(1.0, loop=self.loop)
        except (Exception, BaseException, GeneratorExit, KeyboardInterrupt):
            pass 
Example #4
Source File: base_trainer.py    From fastMRI with MIT License 6 votes vote down vote up
def initial_setup(self, args):
        ############
        logging.info(f"run pid: {os.getpid()} parent: {os.getppid()}")
        logging.info("#########")
        logging.info(args.__dict__)
        logging.info(f"Rank: {args.rank} World_size: {args.world_size}, Run {args.run_name}")

        args.cuda = torch.cuda.is_available()
        logging.info(f"Pytorch version: {torch.__version__}")
        logging.info("Using CUDA: {} CUDA AVAIL: {} #DEVICES: {} VERSION: {}".format(
            args.cuda, torch.cuda.is_available(), torch.cuda.device_count(),
            torch.version.cuda))
        if not args.cuda:
            self.device = 'cpu'
        else:
            self.device = 'cuda'
            cudnn.benchmark = True
            cudnn.enabled = True

        random.seed(args.seed) # The seed needs to be constant between processes.
        torch.manual_seed(args.seed)
        torch.cuda.manual_seed_all(args.seed) 
Example #5
Source File: rtrl_base_env.py    From SenseAct with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def start(self):
        """Starts all manager threads and communicator processes."""
        self._running = True

        # Start the communicator process
        for comm in self._all_comms.values():
            comm.start()

        time.sleep(0.5)  # let the communicator buffer have some packets

        self._new_obs_time = time.time()

        # Create a process/thread to read and write to all communicators
        if self._run_mode == 'multithread':
            # multithread case we don't need the check, but assigning here
            # to keep the polling loop the same
            self._parent_pid = os.getppid()
            self._polling_loop = Thread(target=self._run_loop_)
            self._polling_loop.start()
        elif self._run_mode == 'multiprocess':
            self._parent_pid = os.getpid()
            self._polling_loop = Process(target=self._run_loop_)
            self._polling_loop.start() 
Example #6
Source File: horovod.py    From blueoil with Apache License 2.0 6 votes vote down vote up
def is_enabled():
    if os.getenv("USE_HOROVOD"):
        return True
    ppid = os.getppid()
    if ppid <= 1:
        return False

    parent_process_name = _get_pname(ppid)
    if parent_process_name.startswith("horovodrun") or parent_process_name.startswith("mpirun"):
        if horovod_installed:
            return True
        else:
            print("you're trying to run on horovod, but importing Horovod failed. exit.")
            sys.exit(1)
    else:
        return False


# return True if horovod is not enabled, or enabled and the process is rank 0. 
Example #7
Source File: horovod.py    From blueoil with Apache License 2.0 6 votes vote down vote up
def is_enabled():
    if os.getenv("USE_HOROVOD"):
        return True
    ppid = os.getppid()
    if ppid <= 1:
        return False

    parent_process_name = _get_pname(ppid)
    if parent_process_name.startswith("horovodrun") or parent_process_name.startswith("mpirun"):
        if horovod_installed:
            return True
        else:
            print("you're trying to run on horovod, but importing Horovod failed. exit.")
            sys.exit(1)
    else:
        return False


# return True if horovod is not enabled, or enabled and the process is rank 0. 
Example #8
Source File: watch_orphans.py    From dagster with Apache License 2.0 6 votes vote down vote up
def watch(args):
    if not args or len(args) != 2:
        return

    parent_pid = int(args[0])
    tail_pid = int(args[1])

    if not parent_pid or not tail_pid:
        return

    while True:
        # check if this process has been orphaned, in which case kill the tail_pid
        if os.getppid() == 1:
            try:
                os.kill(tail_pid, signal.SIGTERM)
            except OSError:
                pass
            break
        else:
            time.sleep(1) 
Example #9
Source File: monitor.py    From openrasp-iast with Apache License 2.0 6 votes vote down vote up
def _terminate_modules(self):
        """
        结束其他所有模块
        """
        all_procs = []
        scanner_num = Config().get_config("scanner.max_module_instance")

        for i in range(scanner_num):
            pid = Communicator().get_value("pid", "Scanner_" + str(i))
            if pid != 0:
                all_procs.append(pid)
        all_procs.append(Communicator().get_value("pid", "Preprocessor"))
        all_procs += Communicator().get_pre_http_pid()
        for pid in all_procs:
            if pid != 0:
                self._kill_proc_tree(pid)

        ppid = os.getppid()
        if ppid > 1:
            try:
                p = psutil.Process(ppid)
                p.kill()
            except Exception as e:
                Logger().error("Kill launcher failed", exc_info=e) 
Example #10
Source File: sync.py    From Flask-P2P with MIT License 5 votes vote down vote up
def is_parent_alive(self):
        # If our parent changed then we shut down.
        if self.ppid != os.getppid():
            self.log.info("Parent changed, shutting down: %s", self)
            return False
        return True 
Example #11
Source File: test_posix.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def testNoArgFunctions(self):
        # test posix functions which take no arguments and have
        # no side-effects which we need to cleanup (e.g., fork, wait, abort)
        NO_ARG_FUNCTIONS = [ "ctermid", "getcwd", "getcwdb", "uname",
                             "times", "getloadavg",
                             "getegid", "geteuid", "getgid", "getgroups",
                             "getpid", "getpgrp", "getppid", "getuid", "sync",
                           ]

        for name in NO_ARG_FUNCTIONS:
            posix_func = getattr(posix, name, None)
            if posix_func is not None:
                posix_func()
                self.assertRaises(TypeError, posix_func, 1) 
Example #12
Source File: ggevent.py    From Flask-P2P with MIT License 5 votes vote down vote up
def notify(self):
        super(GeventWorker, self).notify()
        if self.ppid != os.getppid():
            self.log.info("Parent changed, shutting down: %s", self)
            sys.exit(0) 
Example #13
Source File: daemon.py    From shadowsocksR-b with Apache License 2.0 5 votes vote down vote up
def daemon_start(pid_file, log_file):

    def handle_exit(signum, _):
        if signum == signal.SIGTERM:
            sys.exit(0)
        sys.exit(1)

    signal.signal(signal.SIGINT, handle_exit)
    signal.signal(signal.SIGTERM, handle_exit)

    # fork only once because we are sure parent will exit
    pid = os.fork()
    assert pid != -1

    if pid > 0:
        # parent waits for its child
        time.sleep(5)
        sys.exit(0)

    # child signals its parent to exit
    ppid = os.getppid()
    pid = os.getpid()
    if write_pid_file(pid_file, pid) != 0:
        os.kill(ppid, signal.SIGINT)
        sys.exit(1)

    os.setsid()
    signal.signal(signal.SIG_IGN, signal.SIGHUP)

    print('started')
    os.kill(ppid, signal.SIGTERM)

    sys.stdin.close()
    try:
        freopen(log_file, 'a', sys.stdout)
        freopen(log_file, 'a', sys.stderr)
    except IOError as e:
        shell.print_exception(e)
        sys.exit(1) 
Example #14
Source File: util.py    From qpid-python with Apache License 2.0 5 votes vote down vote up
def get_client_properties_with_defaults(provided_client_properties={}, version_property_key="qpid.client_version"):
  ppid = 0
  version = "unidentified"
  try:
    ppid = os.getppid()
  except:
    pass

  try:
    import pkg_resources
    pkg = pkg_resources.require("qpid-python")
    if pkg and pkg[0] and pkg[0].version:
      version = pkg[0].version
  except:
    pass

  client_properties = {"product": "qpid python client",
                       version_property_key : version,
                       "platform": os.name,
                       "qpid.client_process": os.path.basename(sys.argv and sys.argv[0] or ''),
                       "qpid.client_pid": os.getpid(),
                       "qpid.client_ppid": ppid}

  if provided_client_properties:
    client_properties.update(provided_client_properties)
  return client_properties 
Example #15
Source File: poll_compute_logs.py    From dagster with Apache License 2.0 5 votes vote down vote up
def current_process_is_orphaned(parent_pid):
    parent_pid = int(parent_pid)
    if sys.platform == 'win32':
        import psutil  # pylint: disable=import-error

        try:
            parent = psutil.Process(parent_pid)
            return parent.status() != psutil.STATUS_RUNNING
        except psutil.NoSuchProcess:
            return True

    else:
        return os.getppid() != parent_pid 
Example #16
Source File: gtornado.py    From Flask-P2P with MIT License 5 votes vote down vote up
def watchdog(self):
        if self.alive:
            self.notify()

        if self.ppid != os.getppid():
            self.log.info("Parent changed, shutting down: %s", self)
            self.stop() 
Example #17
Source File: simple_core.py    From Python-notes with MIT License 5 votes vote down vote up
def worker_1(interval):
    print("worker_1,父进程(%s),当前进程(%s)" % (os.getppid(), os.getpid()))
    t_start = time.time()
    time.sleep(interval)
    t_end = time.time()
    print("worker_1,执行时间为'%0.2f'秒" % (t_end - t_start)) 
Example #18
Source File: gthread.py    From Flask-P2P with MIT License 5 votes vote down vote up
def is_parent_alive(self):
        # If our parent changed then we shut down.
        if self.ppid != os.getppid():
            self.log.info("Parent changed, shutting down: %s", self)
            return False
        return True 
Example #19
Source File: iostat.py    From scalyr-agent-2 with Apache License 2.0 5 votes vote down vote up
def main():
    """iostats main loop."""
    f_diskstats = open("/proc/diskstats", "r")

    while True:
        # Scalyr edit to add in check for parent.  A ppid of 1 means our parent has died.
        if os.getppid() == 1:
            sys.exit(1)

        parse_and_print_metrics(f_diskstats=f_diskstats)

        sys.stdout.flush()
        time.sleep(COLLECTION_INTERVAL) 
Example #20
Source File: test_os.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def test_getppid(self):
        p = subprocess.Popen([sys.executable, '-c',
                              'import os; print(os.getppid())'],
                             stdout=subprocess.PIPE)
        stdout, _ = p.communicate()
        # We are the parent of our subprocess
        self.assertEqual(int(stdout), os.getpid()) 
Example #21
Source File: simple_core.py    From Python-notes with MIT License 5 votes vote down vote up
def worker_2(interval):
    print("worker_2,父进程(%s),当前进程(%s)" % (os.getppid(), os.getpid()))
    t_start = time.time()
    time.sleep(interval)
    t_end = time.time()
    print("worker_2,执行时间为'%0.2f'秒" % (t_end - t_start)) 
Example #22
Source File: multiprocessing2.py    From advancedpython3 with GNU General Public License v3.0 5 votes vote down vote up
def worker(msg):
    print('module name:', __name__)
    print('parent process:', os.getppid())
    print('process id:', os.getpid())
    for i in range(0, 10):
        print(msg, end='', flush=True)
        sleep(1) 
Example #23
Source File: client.py    From poet with MIT License 5 votes vote down vote up
def daemonize():
    """Daemonize client.
    http://www.jejik.com/articles/2007/02/a_simple_unix_linux_daemon_in_python/
    """

    # already a daemon?
    if os.getppid() == 1:
        return

    # break out of shell
    try:
        pid = os.fork()
        if pid > 0:
            sys.exit(0)
    except OSError:
        # silently faily
        sys.exit(1)

    # standard decoupling
    os.setsid()     # detach from terminal
    os.umask(0022)  # not really necessary, client isn't creating files
    os.chdir('/')   # so we don't block a fs from unmounting

    # denature std fd's
    si = file('/dev/null', 'r')
    so = file('/dev/null', 'a+')
    se = file('/dev/null', 'a+', 0)
    os.dup2(si.fileno(), sys.stdin.fileno())
    os.dup2(so.fileno(), sys.stdout.fileno())
    os.dup2(se.fileno(), sys.stderr.fileno()) 
Example #24
Source File: wolfe.py    From wolfe with MIT License 5 votes vote down vote up
def off():
  command = """PROMPT_COMMAND='l="$(cat /tmp/lasterr)";exec 2>/dev/tty; exec 2> >(tee /tmp/lasterr)'"""
  try:
    with open(os.path.join(os.path.expanduser('~'), '.bashrc'), 'r') as basrhc_file:
        lines = basrhc_file.readlines()
    with open(os.path.join(os.path.expanduser('~'), '.bashrc'), 'w') as basrhc_file:
        for line in lines:
            if not command in line:
                basrhc_file.write(line)
    os.system("kill -9 " + str(os.getppid()))
  except:
    import traceback; traceback.print_exc();
    print 'Unexpected error'
    print 'Back up of bashrc in ~/.bashrc.bak' 
Example #25
Source File: streamcards.py    From mtgencode with MIT License 5 votes vote down vote up
def wait_and_kill_self_noreturn(threads):
    running = True
    while running:
        running = False
        for thread in threads:
            if thread.is_alive():
                running = True
        if(os.getppid() <= 1):
            # exit if parent process died (and we were reparented to init)
            break
        time.sleep(1)
    force_kill_self_noreturn() 
Example #26
Source File: debug.py    From coveragepy-bbmirror with Apache License 2.0 5 votes vote down vote up
def __init__(self, outfile, show_process, filters):
        self.outfile = outfile
        self.show_process = show_process
        self.filters = list(filters)

        if self.show_process:
            self.filters.append(CwdTracker().filter)
            cmd = " ".join(getattr(sys, 'argv', ['???']))
            self.write("New process: executable: %s\n" % (sys.executable,))
            self.write("New process: cmd: %s\n" % (cmd,))
            if hasattr(os, 'getppid'):
                self.write("New process: pid: %s, parent pid: %s\n" % (os.getpid(), os.getppid())) 
Example #27
Source File: yap_tools.py    From yap with Apache License 2.0 5 votes vote down vote up
def check_open_file_desc():
    """ Checks if a particular file descriptor is still open. """
    pid=os.getpid()
    ppid=os.getppid()
    procs=check_output("lsof -w -Ff -p "+str(ppid)) 
Example #28
Source File: daemon.py    From shadowsocksr with Apache License 2.0 5 votes vote down vote up
def daemon_start(pid_file, log_file):

    def handle_exit(signum, _):
        if signum == signal.SIGTERM:
            sys.exit(0)
        sys.exit(1)

    signal.signal(signal.SIGINT, handle_exit)
    signal.signal(signal.SIGTERM, handle_exit)

    # fork only once because we are sure parent will exit
    pid = os.fork()
    assert pid != -1

    if pid > 0:
        # parent waits for its child
        time.sleep(5)
        sys.exit(0)

    # child signals its parent to exit
    ppid = os.getppid()
    pid = os.getpid()
    if write_pid_file(pid_file, pid) != 0:
        os.kill(ppid, signal.SIGINT)
        sys.exit(1)

    os.setsid()
    signal.signal(signal.SIG_IGN, signal.SIGHUP)

    print('started')
    os.kill(ppid, signal.SIGTERM)

    sys.stdin.close()
    try:
        freopen(log_file, 'a', sys.stdout)
        freopen(log_file, 'a', sys.stderr)
    except IOError as e:
        shell.print_exception(e)
        sys.exit(1) 
Example #29
Source File: conf.py    From django-q with MIT License 5 votes vote down vote up
def get_ppid():
    if hasattr(os, "getppid"):
        return os.getppid()
    elif psutil:
        return psutil.Process(os.getpid()).ppid()
    else:
        raise OSError(
            "Your OS does not support `os.getppid`. Please install `psutil` as an alternative provider."
        ) 
Example #30
Source File: graphql.py    From incubator-spot with Apache License 2.0 5 votes vote down vote up
def get_nbserver_info(self):
        profile_loc = IPython.config.get_config()['ProfileDir']['location']
        nbserver_pid = os.getppid()
        nbserver_file = os.path.join(profile_loc, 'security', 'nbserver-{}.json'.format(nbserver_pid))

        try:
            return json.load(open(nbserver_file))
        except:
            return {}