本文整理汇总了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
示例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)
示例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)
示例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()
示例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)
示例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.
示例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)
示例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)
示例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 {}
示例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
示例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()
示例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
示例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
示例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
示例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