本文整理汇总了Python中os.fork方法的典型用法代码示例。如果您正苦于以下问题:Python os.fork方法的具体用法?Python os.fork怎么用?Python os.fork使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类os
的用法示例。
在下文中一共展示了os.fork方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: start
# 需要导入模块: import os [as 别名]
# 或者: from os import fork [as 别名]
def start(self):
if self.finalized:
self.bus.log('Already deamonized.')
# forking has issues with threads:
# http://www.opengroup.org/onlinepubs/000095399/functions/fork.html
# "The general problem with making fork() work in a multi-threaded
# world is what to do with all of the threads..."
# So we check for active threads:
if threading.activeCount() != 1:
self.bus.log('There are %r active threads. '
'Daemonizing now may cause strange failures.' %
threading.enumerate(), level=30)
self.daemonize(self.stdin, self.stdout, self.stderr, self.bus.log)
self.finalized = True
示例2: start_data_processing
# 需要导入模块: import os [as 别名]
# 或者: from os import fork [as 别名]
def start_data_processing(thread_number):
""" TODO: replace with your code.
Most work regarding sending to IF is abstracted away for you.
This function will get the data to send and prepare it for the API.
The general outline should be:
0. Define the project type in config.ini
1. Parse config options
2. Gather data
3. Parse each entry
4. Call the appropriate handoff function
metric_handoff()
log_handoff()
alert_handoff()
incident_handoff()
deployment_handoff()
See zipkin for an example that uses os.fork to send both metric and log data.
"""
示例3: start_data_processing
# 需要导入模块: import os [as 别名]
# 或者: from os import fork [as 别名]
def start_data_processing():
""" get traces from the last <samplingInterval> minutes """
# fork off a process to handle metric agent
parent = os.fork()
if parent > 0:
track['mode'] = "LOG"
if_config_vars['projectName'] += '-log'
logger.debug(str(os.getpid()) + ' is running the log agent')
else:
track['mode'] = "METRIC"
if_config_vars['projectName'] += '-metric'
logger.debug(str(os.getpid()) + ' is running the metric agent')
timestamp_fixed = int(time.time() * 1000)
traces = zipkin_get_traces()
for trace in traces:
for span in trace:
process_zipkin_span(timestamp_fixed, span)
示例4: daemonize
# 需要导入模块: import os [as 别名]
# 或者: from os import fork [as 别名]
def daemonize(logfile = None):
# Fork once
if os.fork() != 0:
os._exit(0)
# Create new session
os.setsid()
if os.fork() != 0:
os._exit(0)
os.chdir('/')
fd = os.open('/dev/null', os.O_RDWR)
os.dup2(fd, sys.__stdin__.fileno())
if logfile != None:
fake_stdout = open(logfile, 'a', 1)
sys.stdout = fake_stdout
sys.stderr = fake_stdout
fd = fake_stdout.fileno()
os.dup2(fd, sys.__stdout__.fileno())
os.dup2(fd, sys.__stderr__.fileno())
if logfile == None:
os.close(fd)
示例5: _init_with_header
# 需要导入模块: import os [as 别名]
# 或者: from os import fork [as 别名]
def _init_with_header(self, header_lines):
# Following pipe is responsible for supplying lines from child process to
# the parent process, which will be fed into PySam object through an actual
# file descriptor.
return_pipe_read, return_pipe_write = os.pipe()
# Since child process doesn't have access to the lines that need to be
# parsed, following pipe is needed to supply them from _get_variant() method
# into the child process, to be propagated back into the return pipe.
send_pipe_read, send_pipe_write = os.pipe()
pid = os.fork()
if pid:
self._process_pid = pid
self._init_parent_process(return_pipe_read, send_pipe_write)
else:
self._init_child_process(send_pipe_read,
return_pipe_write,
header_lines,
self._pre_infer_headers)
示例6: workers
# 需要导入模块: import os [as 别名]
# 或者: from os import fork [as 别名]
def workers(master_host, master_port, relay_socket_path, num_workers):
# Start the relay
master_redis_cfg = {'host': master_host, 'port': master_port}
relay_redis_cfg = {'unix_socket_path': relay_socket_path}
if os.fork() == 0:
RelayClient(master_redis_cfg, relay_redis_cfg).run()
return
# Start the workers
noise = SharedNoiseTable() # Workers share the same noise
num_workers = num_workers if num_workers else os.cpu_count()
logging.info('Spawning {} workers'.format(num_workers))
for _ in range(num_workers):
if os.fork() == 0:
run_worker(relay_redis_cfg, noise=noise)
return
os.wait()
示例7: service_actions
# 需要导入模块: import os [as 别名]
# 或者: from os import fork [as 别名]
def service_actions(self):
"""Called by the serve_forever() loop.
May be overridden by a subclass / Mixin to implement any code that
needs to be run during the loop.
"""
pass
# The distinction between handling, getting, processing and
# finishing a request is fairly arbitrary. Remember:
#
# - handle_request() is the top-level call. It calls
# select, get_request(), verify_request() and process_request()
# - get_request() is different for stream or datagram sockets
# - process_request() is the place that may fork a new process
# or create a new thread to finish the request
# - finish_request() instantiates the request handler class;
# this constructor will handle the request all by itself
示例8: process_request
# 需要导入模块: import os [as 别名]
# 或者: from os import fork [as 别名]
def process_request(self, request, client_address):
"""Fork a new subprocess to process the request."""
pid = os.fork()
if pid:
# Parent process
if self.active_children is None:
self.active_children = []
self.active_children.append(pid)
self.close_request(request)
return
else:
# Child process.
# This must never return, hence os._exit()!
try:
self.finish_request(request, client_address)
self.shutdown_request(request)
os._exit(0)
except:
try:
self.handle_error(request, client_address)
self.shutdown_request(request)
finally:
os._exit(1)
示例9: __init__
# 需要导入模块: import os [as 别名]
# 或者: from os import fork [as 别名]
def __init__(self, fun, args=None, kwargs=None, nice_level=0,
child_on_start=None, child_on_exit=None):
if args is None:
args = []
if kwargs is None:
kwargs = {}
self.fun = fun
self.args = args
self.kwargs = kwargs
self.tempdir = tempdir = py.path.local.mkdtemp()
self.RETVAL = tempdir.ensure('retval')
self.STDOUT = tempdir.ensure('stdout')
self.STDERR = tempdir.ensure('stderr')
pid = os.fork()
if pid: # in parent process
self.pid = pid
else: # in child process
self.pid = None
self._child(nice_level, child_on_start, child_on_exit)
示例10: main
# 需要导入模块: import os [as 别名]
# 或者: from os import fork [as 别名]
def main():
pid_list.append(os.getpid())
child_pid = os.fork()
if child_pid == 0:
pid_list.append(os.getpid())
print()
print("CHLD: hey, I am the child process")
print("CHLD: all the pids i know %s" % pid_list)
else:
pid_list.append(os.getpid())
print()
print("PRNT: hey, I am the parent")
print("PRNT: the child is pid %d" % child_pid)
print("PRNT: all the pids i know %s" % pid_list)
开发者ID:PacktPublishing,项目名称:Expert-Python-Programming_Second-Edition,代码行数:18,代码来源:multiprocessing_forks.py
示例11: maybe_start_cleaner_thread
# 需要导入模块: import os [as 别名]
# 或者: from os import fork [as 别名]
def maybe_start_cleaner_thread(self):
if not self.over_limit():
return
# exit immediately if another cleaner is active
cleaner_lock = os.path.join(self.pcache_dir, ".clean")
if self.lock_file(cleaner_lock, blocking=False):
self.log(INFO, "cleanup not starting: %s locked", cleaner_lock)
return
# see http://www.faqs.org/faqs/unix-faq/faq/part3/section-13.html
# for explanation of double-fork
pid = os.fork()
if pid: # parent
os.waitpid(pid, 0)
return
else: # child
self.daemonize()
pid = os.fork()
if pid:
os._exit(0)
# grandchild
self.clean_cache()
self.unlock_file(cleaner_lock)
os._exit(0)
示例12: prompt
# 需要导入模块: import os [as 别名]
# 或者: from os import fork [as 别名]
def prompt(default=None):
editor = 'nano'
with tempfile.NamedTemporaryFile(mode='r+') as tmpfile:
if default:
tmpfile.write(default)
tmpfile.flush()
child_pid = os.fork()
is_child = child_pid == 0
if is_child:
os.execvp(editor, [editor, tmpfile.name])
else:
os.waitpid(child_pid, 0)
tmpfile.seek(0)
return tmpfile.read().strip()
示例13: start_background_slave_copy
# 需要导入模块: import os [as 别名]
# 或者: from os import fork [as 别名]
def start_background_slave_copy(self, snapshot):
logger.debug('Starting background slave copy')
snapshot_id = snapshot.id
self.raw_conn.close()
self.raw_db.session.close()
self.db.session.close()
pid = os.fork() if hasattr(os, 'fork') else None
if pid:
return
self.init_database()
self.operations = Operations(self.raw_conn, self.config)
snapshot = self.db.session.query(Snapshot).get(snapshot_id)
snapshot.worker_pid = os.getpid()
self.db.session.commit()
self.inline_slave_copy(snapshot)
sys.exit()
示例14: __init__
# 需要导入模块: import os [as 别名]
# 或者: from os import fork [as 别名]
def __init__(self, cmd, bufsize=-1):
_cleanup()
self.cmd = cmd
p2cread, p2cwrite = os.pipe()
c2pread, c2pwrite = os.pipe()
self.pid = os.fork()
if self.pid == 0:
# Child
os.dup2(p2cread, 0)
os.dup2(c2pwrite, 1)
os.dup2(c2pwrite, 2)
self._run_child(cmd)
os.close(p2cread)
self.tochild = os.fdopen(p2cwrite, 'w', bufsize)
os.close(c2pwrite)
self.fromchild = os.fdopen(c2pread, 'r', bufsize)
示例15: shutdown
# 需要导入模块: import os [as 别名]
# 或者: from os import fork [as 别名]
def shutdown(self):
"""Stops the serve_forever loop.
Blocks until the loop has finished. This must be called while
serve_forever() is running in another thread, or it will
deadlock.
"""
self.__shutdown_request = True
self.__is_shut_down.wait()
# The distinction between handling, getting, processing and
# finishing a request is fairly arbitrary. Remember:
#
# - handle_request() is the top-level call. It calls
# select, get_request(), verify_request() and process_request()
# - get_request() is different for stream or datagram sockets
# - process_request() is the place that may fork a new process
# or create a new thread to finish the request
# - finish_request() instantiates the request handler class;
# this constructor will handle the request all by itself