Python os 模块,setsid() 实例源码
我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用os.setsid()。
def _spawn_transform_service(self):
"""Launch transform service and get pid."""
status = 0
pid = os.fork()
if pid == 0:
try:
os.setsid()
# start transform service
launcher = oslo_service.service.launch(
self.conf,
transform_service.Transform(),
workers=1)
status = launcher.wait()
except SystemExit as exc:
traceback.print_exc()
status = exc.code
except BaseException:
try:
traceback.print_exc()
except BaseException:
print("Could not print traceback")
status = 2
os._exit(status or 0)
return pid
def setUp(self):
super(Base, self).setUp()
self.lines = []
self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.sock.bind(("127.0.0.1", 0))
self.t = threading.Thread(target=self.readlog)
self.t.daemon = True
self.t.start()
examplepy = os.path.join(os.path.dirname(__file__),
"examples.py")
if os.name == 'posix':
kwargs = {
'preexec_fn': os.setsid
}
else:
kwargs = {
'creationflags': subprocess.CREATE_NEW_PROCESS_GROUP
}
self.subp = subprocess.Popen(['python', examplepy, self.name,
str(self.sock.getsockname()[1])],
**kwargs)
def spawn(self, command, cwd, env):
"""Starts the process
Spawn a new process and register the listeners on it
Arguments:
command {list} -- command list for the process (ex: ['ls', '-la'])
"""
child_env = os.environ.copy()
child_env.update(env if env is not None else {})
child_env.update({
"TERM":"sublimeterm",
"COLUMNS":"40",
"INPUTRC":"$(pwd)/inputrc"
})
self.master, self.slave = os.openpty()
self.process = subprocess.Popen(command,
stdin=self.slave,
stdout=self.slave,
stderr=self.slave,
preexec_fn=os.setsid,
cwd=cwd,
env=child_env)
def listener(self, name, message):
if FlagSystem.dateUpdated == False:
if message.time_unix_usec != 0: #If GPS messages containing actual date/time have already been received by the SOLO
unix_time = (int) ((message.time_unix_usec)/1000000)
try:
dateUpdate_process = subprocess.Popen('sudo date -s \"'+ str(datetime.datetime.fromtimestamp(unix_time)) +'\"', stdout=subprocess.PIPE, shell=True, preexec_fn=os.setsid)
logger.info('Date and time updated to: %s',str(datetime.datetime.fromtimestamp(unix_time)))
FlagSystem.dateUpdated = True
except Exception as e:
logger.error('Error updating Raspi date and time')
FlagSystem.checkMavlinkMessages += 1
if FlagSystem.checkMavlinkMessages >= 20:
logger.info('MAVLINK messages well received') #Si pas de log pendant plus de 20 secondes, on sait que le lien MAVLINK est perdu...
FlagSystem.checkMavlinkMessages = 0
# Get gimbal tuning
def daemonize():
# See http://www.erlenstar.demon.co.uk/unix/faq_toc.html#TOC16
if os.fork(): # launch child and...
os._exit(0) # kill off parent
os.setsid()
if os.fork(): # launch child and...
os._exit(0) # kill off parent again.
os.umask(077)
null=os.open('/dev/null', os.O_RDWR)
for i in range(3):
try:
os.dup2(null, i)
except OSError, e:
if e.errno != errno.EBADF:
raise
os.close(null)
def closed(self):
global old
log.msg('closed %s' % self)
log.msg(repr(self.conn.channels))
if not options['nocache']: # fork into the background
if os.fork():
if old:
fd = sys.stdin.fileno()
tty.tcsetattr(fd, tty.TCSANOW, old)
if (options['command'] and options['tty']) or \
not options['notty']:
signal.signal(signal.SIGWINCH, signal.SIG_DFL)
os._exit(0)
os.setsid()
for i in range(3):
try:
os.close(i)
except OSError, e:
import errno
if e.errno != errno.EBADF:
raise
def create_forward_port(
self, port, forward_address, forward_port, address=None,
remote=False, **connect_kwargs):
"""
Warning: This can be a security issue for long running tunnels because
bind_address does not work like ssh, instead it default to binding
on every interface. SSH defaults to binding to localhost.
"""
args = self._get_args(**connect_kwargs)
remote_flag = "R" if remote else "L"
args.append("-{0}{1}:{2}:{3}:{4}".format(
remote_flag, address or "0.0.0.0", port,
forward_address, forward_port))
hostname = connect_kwargs.get("hostname", self.hostname)
address = address or hostname if remote else "localhost"
proc = subprocess.Popen(args, preexec_fn=os.setsid)
return PortForward(proc.pid, address=address, port=port)
def generate(self):
return textwrap.dedent("""
import pupy, os
if os.name == 'posix':
pupy.infos['daemonize']=True
if os.fork(): # launch child and...
os._exit(0) # kill off parent
os.setsid()
if os.fork(): # launch child and...
os._exit(0) # kill off parent again.
os.umask(022) # Don't allow others to write
null=os.open('/dev/null', os.O_RDWR)
for i in range(3):
try:
os.dup2(null, i)
except OSError, e:
if e.errno != errno.EBADF:
raise
os.close(null)
""")
def create_daemon(task_id, version):
pid = os.fork()
if pid == 0:
os.setsid()
sub_pid = os.fork()
if sub_pid == 0:
try:
run('supervisorctl restart corvus-agent:')
for _ in range(30):
if program_running('corvus-agent:corvus-agent-api') and \
program_running('corvus-agent:corvus-agent-task'):
break
time.sleep(1)
else:
raise TaskException('Agent updated but not running')
Task.set_status(task_id, Task.DONE)
except Exception:
Task.set_status(task_id, Task.FAILED,
reason=traceback.format_exc())
exit(0)
else:
os._exit(0)
else:
os._exit(0)
def _boot(self):
# Child processes don't start without a HOME dir
if not self.env.get('HOME', False):
raise HerokuStartupError('"HOME" environment not set... aborting.')
port = self.config.get('base_port')
web_dynos = self.config.get('num_dynos_web', 1)
worker_dynos = self.config.get('num_dynos_worker', 1)
commands = [
self.shell_command, 'local', '-p', str(port),
"web={},worker={}".format(web_dynos, worker_dynos)
]
try:
self._process = subprocess.Popen(
commands,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
env=self.env,
preexec_fn=os.setsid,
)
except OSError:
self.out.error("Couldn't start Heroku for local debugging.")
raise
def become_daemon(self, root_dir='/'):
if os.fork() != 0: # launch child and ...
os._exit(0) # kill off parent
os.setsid()
os.chdir(root_dir)
os.umask(0)
if os.fork() != 0: # fork again so we are not a session leader
os._exit(0)
sys.stdin.close()
sys.__stdin__ = sys.stdin
sys.stdout.close()
sys.stdout = sys.__stdout__ = _NullDevice()
sys.stderr.close()
sys.stderr = sys.__stderr__ = _NullDevice()
for fd in range(1024):
try:
os.close(fd)
except OSError:
pass
def start(self):
self.command = "%s %s -%c -R %s -s %d" % \
(
INJECTOR,
" ".join(self.settings.args),
self.settings.synth_mode,
"-0" if self.settings.root else "",
self.settings.seed
)
self.process = subprocess.Popen(
"exec %s" % self.command,
shell=True,
stdout=subprocess.PIPE,
stdin=subprocess.PIPE,
preexec_fn=os.setsid
)
def tty_create_child(*args):
master_fd, slave_fd = os.openpty()
disable_echo(master_fd)
disable_echo(slave_fd)
pid = os.fork()
if not pid:
mitogen.core.set_block(slave_fd)
os.dup2(slave_fd, 0)
os.dup2(slave_fd, 1)
os.dup2(slave_fd, 2)
close_nonstandard_fds()
os.setsid()
os.close(os.open(os.ttyname(1), os.O_RDWR))
os.execvp(args[0], args)
os.close(slave_fd)
LOG.debug('tty_create_child() child %d fd %d, parent %d, cmd: %s',
pid, master_fd, os.getpid(), Argv(args))
return pid, master_fd
def setUpClass(self):
# run main.py with args: --test, and wait for it to terminate
cmd = ["python", "../main.py", "--test"]
self.p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, preexec_fn=os.setsid)
time.sleep(2)
# if not running, check for errors
if self.p.poll() != None:
output, errors = self.p.communicate()
if self.p.returncode:
print self.p.returncode
sys.exit(errors)
else:
print output
# set the python wrapper to client
self.client = BanditClient()
sys.path.insert(0, '../')
from database import get_test_db
# connect to the test db
self.db = get_test_db()
self.db.flushdb()
def generate(self):
return textwrap.dedent("""
import pupy, os
if os.name == 'posix':
pupy.infos['daemonize']=True
if os.fork(): # launch child and...
os._exit(0) # kill off parent
os.setsid()
if os.fork(): # launch child and...
os._exit(0) # kill off parent again.
os.umask(022) # Don't allow others to write
null=os.open('/dev/null', os.O_RDWR)
for i in range(3):
try:
os.dup2(null, i)
except OSError, e:
if e.errno != errno.EBADF:
raise
os.close(null)
""")
def __init__(self, cmd, **kwargs):
start_new_session = kwargs.pop('start_new_session', True)
options = {
'stdout': subprocess.PIPE,
'stderr': subprocess.STDOUT,
'shell': True,
'bufsize': 1,
'close_fds': not ON_WINDOWS,
}
options.update(**kwargs)
if ON_WINDOWS:
# MSDN reference:
# http://msdn.microsoft.com/en-us/library/windows/desktop/ms684863%28v=vs.85%29.aspx
create_new_process_group = 0x00000200
detached_process = 0x00000008
#options.update(creationflags=detached_process | create_new_process_group)
os.environ["COMSPEC"]= "powershell.exe"
elif start_new_session:
if sys.version_info < (3, 2):
options.update(preexec_fn=os.setsid)
else:
options.update(start_new_session=True)
super(PopenPatched, self).__init__(cmd, **options)
def __start_service(mode, debug):
if not debug:
pid = os.fork()
if pid != 0: sys.exit(0)
os.setsid()
os.umask(0)
pid = os.fork()
if pid != 0: sys.exit(0)
proc.write_pid(PID_FILE)
config_path = "%s/fdslight_etc/fn_client.ini" % BASE_DIR
configs = configfile.ini_parse_from_file(config_path)
cls = _fdslight_client()
if debug:
cls.ioloop(mode, debug, configs)
return
try:
cls.ioloop(mode, debug, configs)
except:
logging.print_error()
def __start_service(debug):
if not debug:
pid = os.fork()
if pid != 0: sys.exit(0)
os.setsid()
os.umask(0)
pid = os.fork()
if pid != 0: sys.exit(0)
proc.write_pid(PID_FILE)
configs = configfile.ini_parse_from_file("%s/fdslight_etc/fn_server.ini" % BASE_DIR)
cls = _fdslight_server()
if debug:
cls.ioloop(debug, configs)
return
try:
cls.ioloop(debug, configs)
except:
logging.print_error()
def start_job(self,run_dir,cmd,app,jid,np,myjobs):
"""this is what the separate job process runs"""
for i in range(np): self.sem.acquire()
# update state to 'R' for run
self._set_state(jid,STATE_RUN)
mycwd = os.getcwd()
os.chdir(run_dir) # change to case directory
pro = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True, preexec_fn=os.setsid)
myjobs[jid] = pro
pro.wait() # wait for job to finish
myjobs.pop(long(jid),None) # remove job from buffer
# let user know job has ended
outfn = app + ".out"
with open(outfn,"a") as f:
f.write("FINISHED EXECUTION")
# update state to 'C' for completed
os.chdir(mycwd)
self._set_state(jid,STATE_COMPLETED)
for i in range(np):
self.sem.release()
def createDaemon():
if os.fork() == 0:
os.setsid()
if os.fork() == 0:
os.chdir(os.getcwd())
os.umask(0)
else:
os._exit(0)
else:
os._exit(0)
pid = os.getpid()
print '\nMonast daemonized with pid %s' % pid
f = open(MONAST_PID_FILE, 'w')
f.write('%s' % pid)
f.close()
##
## Main
##
def daemonize():
# See http://www.steve.org.uk/Reference/Unix/faq_2.html#SEC16
if os.fork(): # launch child and...
os._exit(0) # kill off parent
os.setsid()
if os.fork(): # launch child and...
os._exit(0) # kill off parent again.
# some argue that this umask should be 0, but that's annoying.
os.umask(0o077)
null = os.open('/dev/null', os.O_RDWR)
for i in range(3):
try:
os.dup2(null, i)
except OSError as e:
if e.errno != errno.EBADF:
raise
os.close(null)
def start_dropbox():
db_path = os.path.expanduser(u"~/.dropbox-dist/dropboxd").encode(sys.getfilesystemencoding())
if os.access(db_path, os.X_OK):
f = open("/dev/null", "w")
# we don't reap the child because we're gonna die anyway, let init do it
a = subprocess.Popen([db_path], preexec_fn=os.setsid, cwd=os.path.expanduser("~"),
stderr=sys.stderr, stdout=f, close_fds=True)
# in seconds
interval = 0.5
wait_for = 60
for i in xrange(int(wait_for / interval)):
if is_dropbox_running():
return True
# back off from connect for a while
time.sleep(interval)
return False
else:
return False
# Extracted and modified from os.cmd.Cmd
def start(self):
self.cmdline = (self.backend,
'-nostats',
'-loglevel', 'error', # suppress warnings
'-y',
'-r', '%d' % self.frames_per_sec,
# input
'-f', 'rawvideo',
'-s:v', '{}x{}'.format(*self.wh),
'-pix_fmt',('rgb32' if self.includes_alpha else 'rgb24'),
'-i', '-', # this used to be /dev/stdin, which is not Windows-friendly
# output
'-vcodec', 'libx264',
'-pix_fmt', 'yuv420p',
self.output_path
)
logger.debug('Starting ffmpeg with "%s"', ' '.join(self.cmdline))
if hasattr(os,'setsid'): #setsid not present on Windows
self.proc = subprocess.Popen(self.cmdline, stdin=subprocess.PIPE, preexec_fn=os.setsid)
else:
self.proc = subprocess.Popen(self.cmdline, stdin=subprocess.PIPE)
def call(cmd, cwd='.', env=None, capture=False, raise_on_error=True,
timeout=DEFAULT_TIMEOUT):
"""Call invoke command with additional envs and return output."""
env = env or {}
env_str = ' '.join(
['%s="%s"' % (k, v) for k, v in env.iteritems()])
print ('Running:\n cmd: %s %s\n cwd: %s' % (env_str, cmd, cwd)).strip()
final_env = os.environ.copy()
final_env.update(env)
with Popen(
cmd, shell=True, cwd=cwd, env=final_env, preexec_fn=os.setsid,
stdout=subprocess.PIPE if capture else None) as proc:
threading.Thread(target=kill_when_timeout, args=(proc, timeout)).start()
out, _ = proc.communicate()
if proc.returncode != 0 and raise_on_error:
raise subprocess.CalledProcessError(
returncode=proc.returncode, cmd=cmd, output=out)
return proc.returncode, out
def test_capture(self):
"""Test capturing output."""
self.popen.returncode = 0
self.popen.communicate.return_value = ('Test', None)
self.assertEqual(
(0, 'Test'),
process.call('test', cwd='path', env={'NEW': '2'}, capture=True))
self.mock.Popen.assert_called_once_with(
'test', shell=True, cwd='path', env={'TEST': '1', 'NEW': '2'},
stdout=subprocess.PIPE, preexec_fn=os.setsid)
self.popen.communicate.assert_called_once_with()
self.mock.store_last_pid.assert_called_once_with(123)
self.assert_exact_calls(self.mock.kill_last_pid, [mock.call()] * 2)
self.mock.Thread.assert_called_once_with(
target=process.kill_when_timeout,
args=(self.popen, process.DEFAULT_TIMEOUT))
self.mock.Thread.return_value.start.assert_called_once_with()
def test_not_capture(self):
"""Test not capture."""
self.popen.returncode = 0
self.popen.communicate.return_value = (None, None)
self.assertEqual(
(0, None),
process.call('test', cwd='path', env={'NEW': '2'}, capture=False))
self.mock.Popen.assert_called_once_with(
'test', shell=True, cwd='path', env={'TEST': '1', 'NEW': '2'},
stdout=None, preexec_fn=os.setsid)
self.popen.communicate.assert_called_once_with()
self.mock.store_last_pid.assert_called_once_with(123)
self.assert_exact_calls(self.mock.kill_last_pid, [mock.call()] * 2)
self.mock.Thread.assert_called_once_with(
target=process.kill_when_timeout,
args=(self.popen, process.DEFAULT_TIMEOUT))
self.mock.Thread.return_value.start.assert_called_once_with()
def test_error(self):
"""Test raising exception if returncode is not zero."""
self.popen.returncode = 1
self.popen.communicate.return_value = ('Test', None)
with self.assertRaises(subprocess.CalledProcessError) as cm:
process.call('test', cwd='path', env={'NEW': '2'}, capture=False)
self.mock.Popen.assert_called_once_with(
'test', shell=True, cwd='path', env={'TEST': '1', 'NEW': '2'},
stdout=None, preexec_fn=os.setsid)
self.popen.communicate.assert_called_once_with()
self.mock.store_last_pid.assert_called_once_with(123)
self.assert_exact_calls(self.mock.kill_last_pid, [mock.call()] * 2)
self.assertEqual(1, cm.exception.returncode)
self.assertEqual('Test', cm.exception.output)
self.assertEqual('test', cm.exception.cmd)
self.mock.Thread.assert_called_once_with(
target=process.kill_when_timeout,
args=(self.popen, process.DEFAULT_TIMEOUT))
self.mock.Thread.return_value.start.assert_called_once_with()
def execute(binary, args, cwd, print_command=True, print_output=True,
capture_output=True, exit_on_error=True, env=None,
stdout_transformer=None, stderr_transformer=None, timeout=None,
stdin=None, preexec_fn=os.setsid,
redirect_stderr_to_stdout=False,
read_buffer_length=DEFAULT_READ_BUFFER_LENGTH):
"""Execute a bash command."""
proc = start_execute(
binary, args, cwd, env=env, print_command=print_command,
stdin=stdin, preexec_fn=preexec_fn,
redirect_stderr_to_stdout=redirect_stderr_to_stdout)
return wait_execute(
proc=proc, exit_on_error=exit_on_error, capture_output=capture_output,
print_output=print_output, timeout=timeout,
stdout_transformer=stdout_transformer,
stderr_transformer=stderr_transformer,
read_buffer_length=read_buffer_length)
def start(self, start_queue=False, shell=False):
if not self.proc:
logging.info("Starting Engine " + self.name)
try:
self.start_loading()
self.proc=Popen(self.command,shell=shell,bufsize=1,universal_newlines=True,
stdin=PIPE,stdout=PIPE,stderr=STDOUT,env=self.command_env)
#, preexec_fn=os.setsid
#, preexec_fn=self.chuser()
if start_queue:
self.queue=Queue()
self.thread_queue=Thread(target=self.proc_enqueue_output, args=())
self.thread_queue.daemon = True # thread dies with the program
self.thread_queue.start()
self.proc_get_lines(2)
except Exception as err:
logging.error("Can't start engine %s => %s" % (self.name,err))
self.stop_loading()
def daemonize():
# See http://www.erlenstar.demon.co.uk/unix/faq_toc.html#TOC16
if os.fork(): # launch child and...
os._exit(0) # kill off parent
os.setsid()
if os.fork(): # launch child and...
os._exit(0) # kill off parent again.
os.umask(077)
null=os.open('/dev/null', os.O_RDWR)
for i in range(3):
try:
os.dup2(null, i)
except OSError, e:
if e.errno != errno.EBADF:
raise
os.close(null)
def closed(self):
global old
log.msg('closed %s' % self)
log.msg(repr(self.conn.channels))
if not options['nocache']: # fork into the background
if os.fork():
if old:
fd = sys.stdin.fileno()
tty.tcsetattr(fd, tty.TCSANOW, old)
if (options['command'] and options['tty']) or \
not options['notty']:
signal.signal(signal.SIGWINCH, signal.SIG_DFL)
os._exit(0)
os.setsid()
for i in range(3):
try:
os.close(i)
except OSError, e:
import errno
if e.errno != errno.EBADF:
raise
def play(self):
if self._process is None:
if self.station:
fifo_path = self._create_fifo()
if fifo_path:
self._process = subprocess.Popen(self._cmd.format(fifo=fifo_path, url=self.station),
stdin=subprocess.PIPE,
stdout=open('/dev/null', 'w'),
stderr=open('/dev/null', 'w'),
shell=True, preexec_fn=os.setsid)
if self._is_running():
self._volume = 100
else:
print "Error: no station selected"
else:
print "Error: Already playing"
def execute(cmd, stderr_to_stdout=False, stdin=None):
"""Execute a command in the shell and return a tuple (rc, stdout, stderr)"""
if stderr_to_stdout:
stderr = STDOUT
else:
stderr = PIPE
if stdin is None:
_stdin = None
else:
_stdin = PIPE
p = Popen(cmd, close_fds=True, stdin=_stdin, stdout=PIPE, stderr=stderr, preexec_fn=os.setsid)
stdout, stderr = p.communicate(input=stdin)
return p.returncode, stdout, stderr
def daemonize(self):
try:
pid = os.fork()
if pid > 0:
sys.exit(0)
except OSError, e:
sys.stderr.write("fork #1 failed: %d (%s)\n" % (e.errno, e.strerror))
sys.exit(1)
os.chdir("/")
os.setsid()
os.umask(0)
try:
pid = os.fork()
if pid > 0:
sys.exit(0)
except OSError, e:
sys.stderr.write("fork #2 failed: %d (%s)\n" % (e.errno, e.strerror))
sys.exit(1)
sys.stdout.flush()
sys.stderr.flush()
si = file(self.stdin, 'r')
so = file(self.stdout, 'a+')
se = file(self.stderr, 'a+', 0)
os.dup2(si.fileno(), sys.stdin.fileno())
os.dup2(so.fileno(), sys.stdout.fileno())
os.dup2(se.fileno(), sys.stderr.fileno())
atexit.register(self.delpid)
pid = str(os.getpid())
file(self.pidfile,'w+').write("%s\n" % pid)
def daemonize(double_fork=True):
'''Puts process in the background using usual UNIX best practices.'''
try:
os.umask(0o22)
except Exception as e:
raise Exception("Unable to change file creation mask: %s" % e)
os.chdir('/')
# First fork
if double_fork:
try:
pid = os.fork()
if pid > 0:
os._exit(0)
except OSError as e:
raise Exception("Error on first fork: [%d] %s" % (e.errno, e.strerr,))
os.setsid()
# Second fork
try:
pid = os.fork()
if pid > 0:
os._exit(0)
except OSError as e:
raise Exception("Error on second fork: [%d] %s" % (e.errno, e.strerr,))
close_open_files()
os.dup2(os.open(os.devnull, os.O_RDWR), sys.stdin.fileno())
os.dup2(os.open(os.devnull, os.O_RDWR), sys.stdout.fileno())
os.dup2(os.open(os.devnull, os.O_RDWR), sys.stderr.fileno())
def open_maybe_gzip(filename, mode='r'):
if filename.endswith(cr_constants.GZIP_SUFFIX):
gunzip = subprocess.Popen(['gunzip', '-c', filename],
stdout=subprocess.PIPE,
preexec_fn=os.setsid)
return gunzip.stdout
else:
return open(filename, mode)
def daemonize(stdin="/dev/null", stdout="/dev/null", stderr="/dev/null"):
'''
Daemonize current script
'''
try:
pid = os.fork()
if pid > 0:
sys.exit(0)
except OSError, e:
sys.stderr.write ("fork #1 failed: (%d) %s\n" % (e.errno, e.strerror) )
sys.exit(1)
os.chdir("/")
os.umask(0)
os.setsid()
try:
pid = os.fork()
if pid > 0:
sys.exit(0)
except OSError, e:
sys.stderr.write ("fork #2 failed: (%d) %s\n" % (e.errno, e.strerror) )
sys.exit(1)
stdin_par = os.path.dirname(stdin)
stdout_par = os.path.dirname(stdout)
stderr_par = os.path.dirname(stderr)
if not stdin_par:
os.path.makedirs(stdin_par)
if not stdout_par:
os.path.makedirs(stdout_par)
if not stderr_par:
os.path.makedirs(stderr_par)
si = open(stdin, 'r')
so = open(stdout, 'a+')
se = open(stderr, 'a+', 0)
os.dup2(si.fileno(), sys.stdin.fileno())
os.dup2(so.fileno(), sys.stdout.fileno())
os.dup2(se.fileno(), sys.stderr.fileno())
def _preexec_val(self):
return os.setsid if sublime.platform() != "windows" else None
def _daemonize(self):
# double-fork. refer to "Advanced Programming in the UNIX Environment"
try: # first fork
pid = os.fork()
if pid > 0: # first parent
os.waitpid(pid, 0) # wait for second child to start
return False # return to caller of daemonize()
except OSError, e:
self.log('fork #1 failed: %s' % e)
return # return caller of daemonize()
# decouple first parent
os.setsid()
os.chdir("/")
os.umask(0)
ppid = os.getpid() # yes, getpid(). it will be the child's ppid
try: # second fork
self._pid = os.fork()
if self._pid > 0: # second parent. just exit
os._exit(0) # this is the wait() above
except OSError, e:
self.log('fork #2 failed: %s' % e)
os._exit(1)
# wait until ppid changes
while os.getppid() == ppid:
time.sleep(0.1)
return True
def _daemonize(self):
# double-fork. refer to "Advanced Programming in the UNIX Environment"
try: # first fork
pid = os.fork()
if pid > 0: # first parent
os.waitpid(pid, 0) # wait for second child to start
return False # return to caller of daemonize()
except OSError, e:
self.log('fork #1 failed: %s' % e)
return # return caller of daemonize()
# decouple first parent
os.setsid()
os.chdir("/")
os.umask(0)
ppid = os.getpid() # yes, getpid(). it will be the child's ppid
try: # second fork
self._pid = os.fork()
if self._pid > 0: # second parent. just exit
os._exit(0) # this is the wait() above
except OSError, e:
self.log('fork #2 failed: %s' % e)
os._exit(1)
# wait until ppid changes
while os.getppid() == ppid:
time.sleep(0.1)
return True
def takePicture(self, lat, longit, altitude):
self.proc2 = subprocess.Popen("omxplayer" + " -o hdmi videos/pictureTaken4.mp4", stdout=subprocess.PIPE, shell=True, preexec_fn=os.setsid)
try :
pictureTaken=self.api.actTakePicture()
#retrieve name of the picture taken
#actTakePicture return a json Array of array and the name of the picture is given under 'result' field
picturefilestring = pictureTaken['result'][0][0]
#removing the backslashes
picturefilestring = picturefilestring.replace('\\',"")
#get the picture name
picturename = re.search('DSC.*\.JPG', picturefilestring).group(0)
self.picturefilestringList.append(picturefilestring)
self.picturenameList.append(picturename)
self.latList.append(lat)
self.longList.append(longit)
self.altitudeList.append(altitude)
except Exception:
proc5 = subprocess.Popen("omxplayer" + " -o hdmi /mnt/Usb-Solo-Mapper/videos/errorTakingPicture.mp4", stdout=subprocess.PIPE, shell=True, preexec_fn=os.setsid)
proc5.wait()
self.logger.debug('errorTakingPicture!')
#
# Telecharge les photos prises pendant le vol, et ecrit dans les .exif les donnees GPS sauvegardees
#
def run(self):
#Every 10s, we check prospective USB-disconnect messages in kern.log
while self.goOn:
with verrou:
try:
checkProcess = subprocess.Popen("sudo tail -n 5 /var/log/kern.log | grep disconnect >> /mnt/Usb-Solo-Mapper/Logs/usbCheck.log", stdout=subprocess.PIPE, shell=True, preexec_fn=os.setsid)
checkProcess.wait()
usb_file = open("/mnt/Usb-Solo-Mapper/Logs/usbCheck.log", "a")
usb_file.close()
except Exception as e:
self.logger.error('USB check process failed : %s',e)
finally:
time.sleep(10)
def run_checker(self, name, test, out):
cmd = './'+name+' '+test.inp.path+' '+test.out.path+' '+out
r = subprocess.Popen(cmd, shell=True, stdin=subprocess.PIPE,
stderr=subprocess.PIPE,
stdout=subprocess.PIPE,
cwd=MEDIA_ROOT, preexec_fn=os.setsid)
stdout, stderr = r.communicate()
return str(stdout, "utf-8")
def run(self, inp=None):
name = self.get_obj_file_name()
sandbox = Sandbox()
cmd = self.get_run_command(name, sandbox)
start = timer()
stdout = b''
stderr = b''
env = os.environ.copy()
r = subprocess.Popen(cmd, shell=True, stdin=subprocess.PIPE,
stderr=subprocess.PIPE,
stdout=subprocess.PIPE, bufsize=4*1024,
cwd=MEDIA_ROOT, preexec_fn=os.setsid,env=env)
try:
if inp is not None:
stdout, stderr = r.communicate(timeout=timeout, input=inp.encode())
else:
stdout, stderr = r.communicate(timeout=timeout)
print('STDOUT : ' + str(stdout, "utf-8"))
print('STDERR : ' + str(stderr, "utf-8"))
except subprocess.TimeoutExpired as e:
print("Timeout expired")
os.killpg(r.pid, signal.SIGINT)
r.returncode = 124
print('Return Code : ' + str(r.returncode))
if self.lang != 'python':
os.remove(MEDIA_ROOT+'/'+name)
print('Elapsed seconds: {:.2f}'.format(timer() - start))
sandbox.delete_sandbox()
return Result(timer() - start, r.returncode, stdout)
def onConnect():
# if keyAgent and options['agent']:
# cc = protocol.ClientCreator(reactor, SSHAgentForwardingLocal, conn)
# cc.connectUNIX(os.environ['SSH_AUTH_SOCK'])
if hasattr(conn.transport, 'sendIgnore'):
_KeepAlive(conn)
if options.localForwards:
for localPort, hostport in options.localForwards:
s = reactor.listenTCP(localPort,
forwarding.SSHListenForwardingFactory(conn,
hostport,
SSHListenClientForwardingChannel))
conn.localForwards.append(s)
if options.remoteForwards:
for remotePort, hostport in options.remoteForwards:
log.msg('asking for remote forwarding for %s:%s' %
(remotePort, hostport))
conn.requestRemoteForwarding(remotePort, hostport)
reactor.addSystemEventTrigger('before', 'shutdown', beforeShutdown)
if not options['noshell'] or options['agent']:
conn.openChannel(SSHSession())
if options['fork']:
if os.fork():
os._exit(0)
os.setsid()
for i in range(3):
try:
os.close(i)
except OSError, e:
import errno
if e.errno != errno.EBADF:
raise
def fork():
"""fork() -> (pid, master_fd)
Fork and make the child a session leader with a controlling terminal."""
try:
pid, fd = os.forkpty()
except (AttributeError, OSError):
pass
else:
if pid == CHILD:
try:
os.setsid()
except OSError:
# os.forkpty() already set us session leader
pass
return pid, fd
master_fd, slave_fd = openpty()
pid = os.fork()
if pid == CHILD:
# Establish a new session.
os.setsid()
os.close(master_fd)
# Slave becomes stdin/stdout/stderr of child.
os.dup2(slave_fd, STDIN_FILENO)
os.dup2(slave_fd, STDOUT_FILENO)
os.dup2(slave_fd, STDERR_FILENO)
if (slave_fd > STDERR_FILENO):
os.close (slave_fd)
# Explicitly open the tty to make it become a controlling tty.
tmp_fd = os.open(os.ttyname(STDOUT_FILENO), os.O_RDWR)
os.close(tmp_fd)
else:
os.close(slave_fd)
# Parent and child process.
return pid, master_fd
def setUp(self):
super(Base, self).setUp()
examplepy = os.path.join(os.path.dirname(__file__),
"examples.py")
self.subp = subprocess.Popen(['python', examplepy, self.name],
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
close_fds=True,
preexec_fn=os.setsid)
def __init__(self, wait_interval=0.01):
"""Creates the ServiceManager object
:param wait_interval: time between each new process spawn
:type wait_interval: float
"""
if self._process_runner_already_created:
raise RuntimeError("Only one instance of ProcessRunner per "
"application is allowed")
ServiceManager._process_runner_already_created = True
self._wait_interval = wait_interval
self._shutdown = threading.Event()
self._running_services = collections.defaultdict(dict)
self._services = []
self._forktimes = []
self._current_process = None
# Try to create a session id if possible
try:
os.setsid()
except OSError:
pass
self.readpipe, self.writepipe = os.pipe()
signal.signal(signal.SIGTERM, self._clean_exit)
signal.signal(signal.SIGINT, self._fast_exit)
signal.signal(signal.SIGALRM, self._alarm_exit)
signal.signal(signal.SIGHUP, self._reload_services)
def daemonize(self):
"""Deamonize class. UNIX double fork mechanism."""
try:
pid = os.fork()
if pid > 0:
# exit first parent
sys.exit(0)
except OSError as err:
sys.stderr.write('fork #1 failed: {0}\n'.format(err))
sys.exit(1)
# decouple from parent environment
os.chdir('/')
os.setsid()
os.umask(0)
# do second fork
try:
pid = os.fork()
if pid > 0:
# exit from second parent
sys.exit(0)
except OSError as err:
sys.stderr.write('fork #2 failed: {0}\n'.format(err))
sys.exit(1)
# redirect standard file descriptors
sys.stdout.flush()
sys.stderr.flush()
stdi = open(os.devnull, 'r')
stdo = open(os.devnull, 'a+')
stde = open(os.devnull, 'a+')
os.dup2(stdi.fileno(), sys.stdin.fileno())
os.dup2(stdo.fileno(), sys.stdout.fileno())
os.dup2(stde.fileno(), sys.stderr.fileno())
# write pidfile
self.write_pid()
def launch_udocker_container(event, context, command):
lambda_output = "/tmp/%s/lambda-stdout.txt" % request_id
remaining_seconds = get_invocation_remaining_seconds(context)
logger.info("Executing udocker container. Timeout set to %s seconds" % str(remaining_seconds))
with subprocess.Popen(command, stderr=subprocess.STDOUT, stdout=open(lambda_output, "w"), preexec_fn=os.setsid) as process:
try:
process.wait(timeout=remaining_seconds)
except subprocess.TimeoutExpired:
kill_udocker_process(process)
# Processing recursive function
if (is_recursive()):
launch_recursive_lambda(event, context.function_name)
else:
logger.warning("Container timeout")
return lambda_output