def run(self):
self_cmdline = self.get_cmdlime(os.getpid())
pid = os.fork()
if pid < 0:
raise OSError('create subprocess fail')
elif pid == 0:
if self.chdir:
os.chdir(self.chdir)
os.umask(0)
os.setsid()
os.close(0)
if self.logfile:
f = open(self.logfile, 'a')
os.dup2(f.fileno(), 1)
os.dup2(f.fileno(), 2)
else:
os.close(1)
os.close(2)
args = self.cmdline.split()
os.execlp(args[0], *args)
os._exit(-1)
else:
self.pid = pid
self.time = datetime.now().strftime('%Y-%m-%d %H:%m:%S')
while True:
cmdline = self.get_cmdlime(pid)
if cmdline is None or cmdline != self_cmdline:
break
time.sleep(0.05)
if not self.is_alive():
raise OSError('daemon exit')
self.proc_cmdline = cmdline
return pid
python类execlp()的实例源码
def _parse(self, parser):
options, args = parser.parse_args()
if not options.allow_root and self._is_root():
parser.error(
"running as root - " +
"run as a different user or specify the --allow-root " +
"command line option")
if options.python is not None:
os.execlp(options.python, options.python, sys.argv[0], *args)
if sys.version_info < (2, 6):
version = platform.python_version()
parser.error(
"this tool requires python >= 2.6 " +
"(you are running python " + version + "), " +
"use the option -p/--python to define a suitable python " +
"executable")
return options, args
def spawn(argv, master_read=_read, stdin_read=_read):
"""Create a spawned process."""
if type(argv) == type(''):
argv = (argv,)
pid, master_fd = fork()
if pid == CHILD:
os.execlp(argv[0], *argv)
try:
mode = tty.tcgetattr(STDIN_FILENO)
tty.setraw(STDIN_FILENO)
restore = 1
except tty.error: # This is the same as termios.error
restore = 0
try:
_copy(master_fd, master_read, stdin_read)
except (IOError, OSError):
if restore:
tty.tcsetattr(STDIN_FILENO, tty.TCSAFLUSH, mode)
os.close(master_fd)
def run(command):
child_pid = os.fork()
if child_pid == 0:
os.execlp(command[0], *command)
else:
while True:
try:
os.waitpid(child_pid, 0)
except OSError as error:
if error.errno == errno.ECHILD:
# No child processes.
# It has exited already.
break
elif error.errno == errno.EINTR:
# Interrupted system call.
# This happens when resizing the terminal.
pass
else:
# An actual error occurred.
raise
def test(self):
# only supports combined server+client model at the moment
# should support separate I suppose, but nobody uses it
nprocs = self.params.get('nprocs', default=commands.getoutput("nproc"))
args = self.params.get('args', default=None)
args = '%s %s' % (args, nprocs)
pid = os.fork()
if pid: # parent
client = os.path.join(self.sourcedir, 'client.txt')
args = '-c %s %s' % (client, args)
cmd = os.path.join(self.sourcedir, "tbench") + " " + args
# Standard output is verbose and merely makes our debug logs huge
# so we don't retain it. It gets parsed for the results.
self.results = process.system_output(cmd, shell=True)
os.kill(pid, signal.SIGTERM) # clean up the server
else: # child
server = os.path.join(self.sourcedir, 'tbench_srv')
os.execlp(server, server)
pattern = re.compile(r"Throughput (.*?) MB/sec (.*?) procs")
(throughput, procs) = pattern.findall(self.results)[0]
self.log.info({'throughput': throughput, 'procs': procs})
def spawn(argv, master_read=_read, stdin_read=_read):
"""Create a spawned process."""
if type(argv) == type(''):
argv = (argv,)
pid, master_fd = fork()
if pid == CHILD:
os.execlp(argv[0], *argv)
try:
mode = tty.tcgetattr(STDIN_FILENO)
tty.setraw(STDIN_FILENO)
restore = 1
except tty.error: # This is the same as termios.error
restore = 0
try:
_copy(master_fd, master_read, stdin_read)
except (IOError, OSError):
if restore:
tty.tcsetattr(STDIN_FILENO, tty.TCSAFLUSH, mode)
os.close(master_fd)
def shell(ctx, python=False, ipython=False, django=False):
"""
Executes the interpreter.
"""
if ipython:
try:
import IPython
except ImportError:
print('IPython not available, running regular Python shell.')
os.execlp(sys.executable, '-i')
else:
os.execlp('ipython3', '-i')
elif django:
os.execlp(sys.executable, 'manage.py', 'shell')
elif python:
os.execlp(sys.executable, '-i')
else:
os.execlp('bash', '-i')
def spawn(argv, master_read=_read, stdin_read=_read):
"""Create a spawned process."""
if type(argv) == type(''):
argv = (argv,)
pid, master_fd = fork()
if pid == CHILD:
os.execlp(argv[0], *argv)
try:
mode = tty.tcgetattr(STDIN_FILENO)
tty.setraw(STDIN_FILENO)
restore = 1
except tty.error: # This is the same as termios.error
restore = 0
try:
_copy(master_fd, master_read, stdin_read)
except (IOError, OSError):
if restore:
tty.tcsetattr(STDIN_FILENO, tty.TCSAFLUSH, mode)
os.close(master_fd)
def spawn(argv, master_read=_read, stdin_read=_read):
"""Create a spawned process."""
if type(argv) == type(''):
argv = (argv,)
pid, master_fd = fork()
if pid == CHILD:
os.execlp(argv[0], *argv)
try:
mode = tty.tcgetattr(STDIN_FILENO)
tty.setraw(STDIN_FILENO)
restore = 1
except tty.error: # This is the same as termios.error
restore = 0
try:
_copy(master_fd, master_read, stdin_read)
except (IOError, OSError):
if restore:
tty.tcsetattr(STDIN_FILENO, tty.TCSAFLUSH, mode)
os.close(master_fd)
def spawn(argv, master_read=_read, stdin_read=_read):
"""Create a spawned process."""
if type(argv) == type(''):
argv = (argv,)
pid, master_fd = fork()
if pid == CHILD:
os.execlp(argv[0], *argv)
try:
mode = tty.tcgetattr(STDIN_FILENO)
tty.setraw(STDIN_FILENO)
restore = 1
except tty.error: # This is the same as termios.error
restore = 0
try:
_copy(master_fd, master_read, stdin_read)
except (IOError, OSError):
if restore:
tty.tcsetattr(STDIN_FILENO, tty.TCSAFLUSH, mode)
os.close(master_fd)
def default_bottom_halves_after_sync(self, *args, **kwargs):
if self.func is None:
if not self.nscmd:
self.nscmd = [find_shell()]
elif not isinstance(self.nscmd, list):
self.nscmd = [self.nscmd]
if "pid" not in self.namespaces:
args = self.nscmd
elif self.init_prog is not None:
args = [self.init_prog] + self.nscmd
else:
args = [sys.executable, self.my_init, "--skip-startup-files",
"--skip-runit", "--quiet"] + self.nscmd
os.execlp(args[0], *args)
else:
if hasattr(self.func, '__call__'):
self.func(*args, **kwargs)
else:
raise NamespaceSettingError()
def spawn(self, argv):
'''
Create a spawned process.
Based on the code for pty.spawn().
'''
assert self.master_fd is None
assert isinstance(argv, list)
pid, master_fd = pty.fork()
self.master_fd = master_fd
if pid == pty.CHILD:
os.execlp(argv[0], *argv) # and not ever returned
self._init()
try:
self._copy() # start communication
except Exception:
# unexpected errors
self._del()
raise
self._del()
return self.log.decode()
def execute(args):
command = args.command
if command and command[0] == '--':
command = command[1:]
if not command:
print('No command to execute provided', file=sys.stderr)
raise SystemExit(1)
if args.filename:
data = yaml.load_file_or_die(args.filename)
env_dict = EnvironmentDict.from_yaml_dict(data)
else:
data = load_user_data_as_yaml_or_die(args.ignoremissing)
env_dict = EnvironmentDict.from_yaml_dict(data)
unencrypted_env_dict = env_dict.decrypt_all_encrypted(plain=True)
os.environ.update(unencrypted_env_dict)
os.execlp(command[0], *command)
def spawn(argv, master_read=_read, stdin_read=_read):
"""Create a spawned process."""
if type(argv) == type(''):
argv = (argv,)
pid, master_fd = fork()
if pid == CHILD:
os.execlp(argv[0], *argv)
try:
mode = tty.tcgetattr(STDIN_FILENO)
tty.setraw(STDIN_FILENO)
restore = 1
except tty.error: # This is the same as termios.error
restore = 0
try:
_copy(master_fd, master_read, stdin_read)
except OSError:
if restore:
tty.tcsetattr(STDIN_FILENO, tty.TCSAFLUSH, mode)
os.close(master_fd)
def spawn(argv, master_read=_read, stdin_read=_read):
"""Create a spawned process."""
if type(argv) == type(''):
argv = (argv,)
pid, master_fd = fork()
if pid == CHILD:
os.execlp(argv[0], *argv)
try:
mode = tty.tcgetattr(STDIN_FILENO)
tty.setraw(STDIN_FILENO)
restore = 1
except tty.error: # This is the same as termios.error
restore = 0
try:
_copy(master_fd, master_read, stdin_read)
except (IOError, OSError):
if restore:
tty.tcsetattr(STDIN_FILENO, tty.TCSAFLUSH, mode)
os.close(master_fd)
def spawn(argv, master_read=_read, stdin_read=_read):
"""Create a spawned process."""
if type(argv) == type(''):
argv = (argv,)
pid, master_fd = fork()
if pid == CHILD:
os.execlp(argv[0], *argv)
try:
mode = tty.tcgetattr(STDIN_FILENO)
tty.setraw(STDIN_FILENO)
restore = 1
except tty.error: # This is the same as termios.error
restore = 0
try:
_copy(master_fd, master_read, stdin_read)
except OSError:
if restore:
tty.tcsetattr(STDIN_FILENO, tty.TCSAFLUSH, mode)
os.close(master_fd)
return os.waitpid(pid, 0)[1]
def spawn(argv, master_read=_read, stdin_read=_read):
"""Create a spawned process."""
if type(argv) == type(''):
argv = (argv,)
pid, master_fd = fork()
if pid == CHILD:
os.execlp(argv[0], *argv)
try:
mode = tty.tcgetattr(STDIN_FILENO)
tty.setraw(STDIN_FILENO)
restore = 1
except tty.error: # This is the same as termios.error
restore = 0
try:
_copy(master_fd, master_read, stdin_read)
except (IOError, OSError):
if restore:
tty.tcsetattr(STDIN_FILENO, tty.TCSAFLUSH, mode)
os.close(master_fd)
def spawn(argv, master_read=_read, stdin_read=_read):
"""Create a spawned process."""
if type(argv) == type(''):
argv = (argv,)
pid, master_fd = fork()
if pid == CHILD:
os.execlp(argv[0], *argv)
try:
mode = tty.tcgetattr(STDIN_FILENO)
tty.setraw(STDIN_FILENO)
restore = 1
except tty.error: # This is the same as termios.error
restore = 0
try:
_copy(master_fd, master_read, stdin_read)
except OSError:
if restore:
tty.tcsetattr(STDIN_FILENO, tty.TCSAFLUSH, mode)
os.close(master_fd)
return os.waitpid(pid, 0)[1]
def nginx(ctx, exec=True):
"""
Start Nginx proxy server.
"""
run('nginx -p /var/www/ -c /etc/nginx/nginx.conf')
if exec:
os.execlp('nginx', '-p', '/var/www/', '-c', '/etc/nginx/nginx.conf')
else:
run('nginx -p /var/www/ -c /etc/nginx/nginx.conf')
def gunicorn(ctx, exec=True):
"""
Starts Gunicorn application server.
"""
if exec:
wsgi_application = os.environ['WSGI_APPLICATION']
sock = 'unix:/tmp/gunicorn.sock'
os.execlp('gunicorn', '-b', sock, wsgi_application, '--reload')
else:
cmd = 'gunicorn $WSGI_APPLICATION -b unix:/tmp/webapp.sock --reload'
ctx.run(cmd, pty=True)
def start(ctx, system=True):
"""
Start both Nginx and Gunicorn under Circus supervision (#TODO!).
"""
# os.execlp('circusd', '--daemon', '/etc/circus.ini')
#os.spawnlp(os.P_NOWAIT, 'nginx', '-p', '/var/www', '-c', '/etc/nginx/nginx.conf')
wsgi = os.environ.get('WSGI_APPLICATION', 'app')
if system:
ctx.run('nginx -p /var/www -c /etc/nginx/nginx.conf')
ctx.run('gunicorn -b unix:/tmp/webapp.sock %s --reload' % wsgi, pty=True)
else:
ctx.run('nginx -p /var/www -c /etc/nginx/nginx.conf')
sock = 'unix:/tmp/gunicorn.sock'
os.execlp('gunicorn', '-b', sock, wsgi, '--reload')
def dev(ctx):
"""
Runs Django's development server.
"""
os.execlp(sys.executable, 'manage.py', 'runserver', '0.0.0.0:80')
def main():
args = get_options()
if args.show_id:
show_current_users_and_groups()
sys.exit(0)
mamaji_data = fetch_mamaji_data(args)
filter_options(mamaji_data)
target_cmd = None
if args.cmd:
target_cmd = args.cmd
if not args.do_fork:
change_users_and_groups(mamaji_data)
# if target_cmd is None, do nothing
if target_cmd:
os.execlp(target_cmd[0], *target_cmd)
sys.exit(0)
if args.do_fork and not args.cmd:
target_cmd = [find_shell()]
pid = os.fork()
if pid == -1:
warn('failed to do fork')
sys.exit(1)
elif pid == 0:
change_users_and_groups(mamaji_data)
os.execlp(target_cmd[0], *target_cmd)
else:
status = os.wait4(pid, 0)[1] >> 8
sys.exit(status)
def create_execl(original_name):
def new_execl(path, *args):
"""
os.execl(path, arg0, arg1, ...)
os.execle(path, arg0, arg1, ..., env)
os.execlp(file, arg0, arg1, ...)
os.execlpe(file, arg0, arg1, ..., env)
"""
import os
args = patch_args(args)
send_process_created_message()
return getattr(os, original_name)(path, *args)
return new_execl
def patch_new_process_functions_with_warning():
monkey_patch_os('execl', create_warn_multiproc)
monkey_patch_os('execle', create_warn_multiproc)
monkey_patch_os('execlp', create_warn_multiproc)
monkey_patch_os('execlpe', create_warn_multiproc)
monkey_patch_os('execv', create_warn_multiproc)
monkey_patch_os('execve', create_warn_multiproc)
monkey_patch_os('execvp', create_warn_multiproc)
monkey_patch_os('execvpe', create_warn_multiproc)
monkey_patch_os('spawnl', create_warn_multiproc)
monkey_patch_os('spawnle', create_warn_multiproc)
monkey_patch_os('spawnlp', create_warn_multiproc)
monkey_patch_os('spawnlpe', create_warn_multiproc)
monkey_patch_os('spawnv', create_warn_multiproc)
monkey_patch_os('spawnve', create_warn_multiproc)
monkey_patch_os('spawnvp', create_warn_multiproc)
monkey_patch_os('spawnvpe', create_warn_multiproc)
if sys.platform != 'win32':
monkey_patch_os('fork', create_warn_multiproc)
try:
import _posixsubprocess
monkey_patch_module(_posixsubprocess, 'fork_exec', create_warn_fork_exec)
except ImportError:
pass
else:
# Windows
try:
import _subprocess
except ImportError:
import _winapi as _subprocess
monkey_patch_module(_subprocess, 'CreateProcess', create_CreateProcessWarnMultiproc)
def spawn(self, argv=None):
'''
Create a spawned process.
Based on the code for pty.spawn().
'''
assert self.master_fd is None
pid, master_fd = pty.fork()
self.master_fd = master_fd
self.pid = pid
if pid == pty.CHILD:
if self.user is not None:
try:
uid = pwd.getpwnam(self.user).pw_uid
except KeyError:
log.error("No such user: %s", self.user)
else:
os.setuid(uid)
log.debug('switched user for remote process to %s(%s)', self.user, uid)
if self.group is not None:
try:
gid = grp.getgrnam(self.group).gr_gid
except KeyError:
log.error("No such group: %s", self.group)
else:
os.setgid(gid)
log.debug('switched group for remote process to %s(%s)', self.group, gid)
if not argv:
argv = [os.environ['SHELL']]
os.execlp(argv[0], *argv)
# Previous command replaces the process
return
self._init_fd()
try:
self._copy()
except (IOError, OSError):
pass
os.close(master_fd)
self.master_fd = None
def main():
setup_env()
os.execlp(sys.argv[1], *sys.argv[1:])
def main(args):
os.system('sudo -p "Sudo password: " echo')
pid = os.fork()
if pid == 0:
time.sleep(0.5)
os.execlp(args.command[0], *args.command)
else:
os.system('sudo dtruss -f -p %d' % (pid))
def open_text_file(self, path):
pid1 = os.fork()
if pid1 == 0:
pid2 = os.fork()
if pid2 == 0:
editor = _unix_editor()
LOG.debug("calling `%s %s'" % (editor, path))
os.execlp(editor, editor, path)
else:
sys.exit(0)
else:
os.waitpid(pid1, 0)
LOG.debug("Exec child exited")
def patch_new_process_functions():
# os.execl(path, arg0, arg1, ...)
# os.execle(path, arg0, arg1, ..., env)
# os.execlp(file, arg0, arg1, ...)
# os.execlpe(file, arg0, arg1, ..., env)
# os.execv(path, args)
# os.execve(path, args, env)
# os.execvp(file, args)
# os.execvpe(file, args, env)
monkey_patch_os('execl', create_execl)
monkey_patch_os('execle', create_execl)
monkey_patch_os('execlp', create_execl)
monkey_patch_os('execlpe', create_execl)
monkey_patch_os('execv', create_execv)
monkey_patch_os('execve', create_execve)
monkey_patch_os('execvp', create_execv)
monkey_patch_os('execvpe', create_execve)
# os.spawnl(mode, path, ...)
# os.spawnle(mode, path, ..., env)
# os.spawnlp(mode, file, ...)
# os.spawnlpe(mode, file, ..., env)
# os.spawnv(mode, path, args)
# os.spawnve(mode, path, args, env)
# os.spawnvp(mode, file, args)
# os.spawnvpe(mode, file, args, env)
monkey_patch_os('spawnl', create_spawnl)
monkey_patch_os('spawnle', create_spawnl)
monkey_patch_os('spawnlp', create_spawnl)
monkey_patch_os('spawnlpe', create_spawnl)
monkey_patch_os('spawnv', create_spawnv)
monkey_patch_os('spawnve', create_spawnve)
monkey_patch_os('spawnvp', create_spawnv)
monkey_patch_os('spawnvpe', create_spawnve)
if sys.platform != 'win32':
monkey_patch_os('fork', create_fork)
try:
import _posixsubprocess
monkey_patch_module(_posixsubprocess, 'fork_exec', create_fork_exec)
except ImportError:
pass
else:
# Windows
try:
import _subprocess
except ImportError:
import _winapi as _subprocess
monkey_patch_module(_subprocess, 'CreateProcess', create_CreateProcess)