當前位置: 首頁>>代碼示例>>Python>>正文


Python os.getppid方法代碼示例

本文整理匯總了Python中os.getppid方法的典型用法代碼示例。如果您正苦於以下問題:Python os.getppid方法的具體用法?Python os.getppid怎麽用?Python os.getppid使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在os的用法示例。


在下文中一共展示了os.getppid方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: _check_alive

# 需要導入模塊: import os [as 別名]
# 或者: from os import getppid [as 別名]
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 
開發者ID:huge-success,項目名稱:sanic,代碼行數:24,代碼來源:worker.py

示例2: startEventLoop

# 需要導入模塊: import os [as 別名]
# 或者: from os import getppid [as 別名]
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) 
開發者ID:SrikanthVelpuri,項目名稱:tf-pose,代碼行數:20,代碼來源:processes.py

示例3: test_ppid

# 需要導入模塊: import os [as 別名]
# 或者: from os import getppid [as 別名]
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) 
開發者ID:birforce,項目名稱:vnpy_crypto,代碼行數:21,代碼來源:test_process.py

示例4: start

# 需要導入模塊: import os [as 別名]
# 或者: from os import getppid [as 別名]
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() 
開發者ID:kindredresearch,項目名稱:SenseAct,代碼行數:25,代碼來源:rtrl_base_env.py

示例5: initial_setup

# 需要導入模塊: import os [as 別名]
# 或者: from os import getppid [as 別名]
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) 
開發者ID:facebookresearch,項目名稱:fastMRI,代碼行數:24,代碼來源:base_trainer.py

示例6: is_enabled

# 需要導入模塊: import os [as 別名]
# 或者: from os import getppid [as 別名]
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. 
開發者ID:blue-oil,項目名稱:blueoil,代碼行數:21,代碼來源:horovod.py

示例7: _terminate_modules

# 需要導入模塊: import os [as 別名]
# 或者: from os import getppid [as 別名]
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) 
開發者ID:baidu-security,項目名稱:openrasp-iast,代碼行數:26,代碼來源:monitor.py

示例8: watch

# 需要導入模塊: import os [as 別名]
# 或者: from os import getppid [as 別名]
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) 
開發者ID:dagster-io,項目名稱:dagster,代碼行數:22,代碼來源:watch_orphans.py

示例9: get_nbserver_info

# 需要導入模塊: import os [as 別名]
# 或者: from os import getppid [as 別名]
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 {} 
開發者ID:apache,項目名稱:incubator-spot,代碼行數:11,代碼來源:graphql.py

示例10: __init__

# 需要導入模塊: import os [as 別名]
# 或者: from os import getppid [as 別名]
def __init__(self, callback=None):
        if os.name == 'nt':
            self._ppid = 0
        else:
            self._ppid = os.getppid()
        self._callback = callback 
開發者ID:remg427,項目名稱:misp42splunk,代碼行數:8,代碼來源:orphan_process_monitor.py

示例11: is_orphan

# 需要導入模塊: import os [as 別名]
# 或者: from os import getppid [as 別名]
def is_orphan(self):
        '''Check process is orphan.

        For windows platform just return False.

        :returns: True for orphan process else False
        :rtype: ``bool``
        '''

        if os.name == 'nt':
            return False
        return self._ppid != os.getppid() 
開發者ID:remg427,項目名稱:misp42splunk,代碼行數:14,代碼來源:orphan_process_monitor.py

示例12: __init__

# 需要導入模塊: import os [as 別名]
# 或者: from os import getppid [as 別名]
def __init__(self, callback=None):
        """
        Only work for Linux platform. On Windows platform, is_orphan is always
        False
        """

        if os.name == "nt":
            self._ppid = 0
        else:
            self._ppid = os.getppid()
        self._callback = callback 
開發者ID:remg427,項目名稱:misp42splunk,代碼行數:13,代碼來源:orphan_process_monitor.py

示例13: is_orphan

# 需要導入模塊: import os [as 別名]
# 或者: from os import getppid [as 別名]
def is_orphan(self):
        if os.name == "nt":
            return False
        res = self._ppid != os.getppid()
        if res:
            log.logger.warn("Process=%s has become orphan", os.getpid())
        return res 
開發者ID:remg427,項目名稱:misp42splunk,代碼行數:9,代碼來源:orphan_process_monitor.py

示例14: ppid_of

# 需要導入模塊: import os [as 別名]
# 或者: from os import getppid [as 別名]
def ppid_of(self, pid=None):
        if pid is None:
            return os.getppid()
        try:
            return int(next(open('/proc/%d/stat' % pid)).split()[3])
        except (OSError, ValueError, IOError):
            return None 
開發者ID:dlenski,項目名稱:vpn-slice,代碼行數:9,代碼來源:linux.py

示例15: ppid_of

# 需要導入模塊: import os [as 別名]
# 或者: from os import getppid [as 別名]
def ppid_of(self, pid=None):
        if pid is None:
            return os.getppid()
        try:
            return int(subprocess.check_output([self.ps, '-p', str(pid), '-o', 'ppid=']))
        except ValueError:
            return None 
開發者ID:dlenski,項目名稱:vpn-slice,代碼行數:9,代碼來源:mac.py


注:本文中的os.getppid方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。