本文整理汇总了Python中os.setsid方法的典型用法代码示例。如果您正苦于以下问题:Python os.setsid方法的具体用法?Python os.setsid怎么用?Python os.setsid使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类os
的用法示例。
在下文中一共展示了os.setsid方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: start
# 需要导入模块: import os [as 别名]
# 或者: from os import setsid [as 别名]
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
)
示例2: daemonize
# 需要导入模块: import os [as 别名]
# 或者: from os import setsid [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)
示例3: start_http_server
# 需要导入模块: import os [as 别名]
# 或者: from os import setsid [as 别名]
def start_http_server(self, port=80):
"""Starts a simple http server on a choosen port.
:port: integer defaults to 80
"""
if(self.__http is None):
cmd = "python -m SimpleHTTPServer %d" % port
try:
self.__http = Popen(cmd, shell=True, preexec_fn=setsid)
logger.info(
'HMI%d - HTTP server started on port %d' % (
self.__id, port))
except OSError, e:
emsg = repr(e)
logger.warning(
'HMI%d - HTTP server cannot start: %s' % (
self.__id, emsg))
示例4: start
# 需要导入模块: import os [as 别名]
# 或者: from os import setsid [as 别名]
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)
示例5: start
# 需要导入模块: import os [as 别名]
# 或者: from os import setsid [as 别名]
def start(self):
if self.is_active:
print(f"[Cluster {self.id}] Already active.")
return
self.started_at = time.time()
self._process = await asyncio.create_subprocess_shell(
self.command,
stdin=asyncio.subprocess.DEVNULL,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE,
preexec_fn=os.setsid,
limit=1024 * 256,
)
self.status = "running"
self.started_at = time.time()
print(f"[Cluster {self.id}] The cluster is starting.")
await asyncio.wait([self.read_stream(self._process.stdout), self.read_stream(self._process.stderr)])
return self
示例6: setUp
# 需要导入模块: import os [as 别名]
# 或者: from os import setsid [as 别名]
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)
示例7: test_mockPTYSetUid
# 需要导入模块: import os [as 别名]
# 或者: from os import setsid [as 别名]
def test_mockPTYSetUid(self):
"""
Try creating a PTY process with setting its uid: it's almost the same
path as the standard path, but with a C{switchUID} call before the
exec.
"""
cmd = b'/mock/ouch'
d = defer.Deferred()
p = TrivialProcessProtocol(d)
try:
reactor.spawnProcess(p, cmd, [b'ouch'], env=None,
usePTY=True, uid=8081)
except SystemError:
self.assertTrue(self.mockos.exited)
self.assertEqual(
self.mockos.actions,
[('fork', False), 'setsid', ('setuid', 0), ('setgid', 0),
('switchuid', 8081, 1234), 'exec', ('exit', 1)])
else:
self.fail("Should not be here")
示例8: launch_proc_with_pty
# 需要导入模块: import os [as 别名]
# 或者: from os import setsid [as 别名]
def launch_proc_with_pty(args, stdin=None, stdout=None, stderr=None, echo=True):
"""Similar to pty.fork, but handle stdin/stdout according to parameters
instead of connecting to the pty
:return tuple (subprocess.Popen, pty_master)
"""
def set_ctty(ctty_fd, master_fd):
os.setsid()
os.close(master_fd)
fcntl.ioctl(ctty_fd, termios.TIOCSCTTY, 0)
if not echo:
termios_p = termios.tcgetattr(ctty_fd)
# termios_p.c_lflags
termios_p[3] &= ~termios.ECHO
termios.tcsetattr(ctty_fd, termios.TCSANOW, termios_p)
(pty_master, pty_slave) = os.openpty()
# pylint: disable=not-an-iterable
p = yield from asyncio.create_subprocess_exec(*args,
stdin=stdin,
stdout=stdout,
stderr=stderr,
preexec_fn=lambda: set_ctty(pty_slave, pty_master))
os.close(pty_slave)
return p, open(pty_master, 'wb+', buffering=0)
示例9: _daemonize
# 需要导入模块: import os [as 别名]
# 或者: from os import setsid [as 别名]
def _daemonize(self):
try:
pid = os.fork() # 第一次fork,生成子进程,脱离父进程
if pid > 0:
sys.exit(0) # 退出主进程
except OSError as e:
sys.stderr.write('fork #1 failed: %d (%s)\n' % (e.errno, e.strerror))
sys.exit(1)
if self.cd:
os.chdir("/") # 修改工作目录
os.setsid() # 设置新的会话连接
os.umask(0) # 重新设置文件创建权限
try:
pid = os.fork() # 第二次fork,禁止进程打开终端
if pid > 0:
sys.exit(0)
except OSError as e:
sys.stderr.write('fork #2 failed: %d (%s)\n' % (e.errno, e.strerror))
sys.exit(1)
# 重定向文件描述符
sys.stdout.flush()
sys.stderr.flush()
# with open(self.stdin, 'r') as si, open(self.stdout, 'a+') as so, open(self.stderr, 'ab+', 0) as se:
si = open(self.stdin, 'r')
so = open(self.stdout, 'a+')
se = open(self.stderr, 'ab+', 0)
os.dup2(si.fileno(), sys.stdin.fileno())
os.dup2(so.fileno(), sys.stdout.fileno())
os.dup2(se.fileno(), sys.stderr.fileno())
# 注册退出函数,根据文件pid判断是否存在进程
atexit.register(self.delpid)
pid = str(os.getpid())
with open(self.pidfile, 'w+') as f:
f.write('%s\n' % pid)
# file(self.pidfile, 'w+').write('%s\n' % pid)
示例10: daemon_start
# 需要导入模块: import os [as 别名]
# 或者: from os import setsid [as 别名]
def daemon_start(pid_file, log_file):
def handle_exit(signum, _):
if signum == signal.SIGTERM:
sys.exit(0)
sys.exit(1)
signal.signal(signal.SIGINT, handle_exit)
signal.signal(signal.SIGTERM, handle_exit)
# fork only once because we are sure parent will exit
pid = os.fork()
assert pid != -1
if pid > 0:
# parent waits for its child
time.sleep(5)
sys.exit(0)
# child signals its parent to exit
ppid = os.getppid()
pid = os.getpid()
if write_pid_file(pid_file, pid) != 0:
os.kill(ppid, signal.SIGINT)
sys.exit(1)
os.setsid()
signal.signal(signal.SIGHUP, signal.SIG_IGN)
print('started')
os.kill(ppid, signal.SIGTERM)
sys.stdin.close()
try:
freopen(log_file, 'a', sys.stdout)
freopen(log_file, 'a', sys.stderr)
except IOError as e:
shell.print_exception(e)
sys.exit(1)
示例11: start
# 需要导入模块: import os [as 别名]
# 或者: from os import setsid [as 别名]
def start(self):
cmd = 'python -m SimpleHTTPServer {port}'.format(port=self.port)
self.server = subprocess.Popen(cmd, shell=True, preexec_fn=os.setsid)
wait_http('localhost', self.port, 200, timeout=5)
示例12: daemonize
# 需要导入模块: import os [as 别名]
# 或者: from os import setsid [as 别名]
def daemonize(self):
if self.debug:
return
try:
os.setsid()
except OSError:
pass
try:
os.chdir("/")
except OSError:
pass
try:
os.umask(0)
except OSError:
pass
n = os.open("/dev/null", os.O_RDWR)
i, o, e = sys.stdin.fileno(), sys.stdout.fileno(), sys.stderr.fileno()
os.dup2(n, i)
os.dup2(n, o)
os.dup2(n, e)
MAXFD = 1024
try:
import resource # Resource usage information.
maxfd = resource.getrlimit(resource.RLIMIT_NOFILE)[1]
if (maxfd == resource.RLIM_INFINITY):
maxfd = MAXFD
except:
try:
maxfd = os.sysconf("SC_OPEN_MAX")
except:
maxfd = MAXFD # use default value
for fd in range(0, maxfd + 1):
try:
os.close(fd)
except:
pass
# Panda server callback functions
示例13: run_cmd_process
# 需要导入模块: import os [as 别名]
# 或者: from os import setsid [as 别名]
def run_cmd_process(cmd, timeout=3600):
"""
shell command parser with timeout
:param cmd: shell command as a string
:param timeout: in seconds
:return: stdout xor stderr, and errorcode
"""
time_start = datetime.datetime.now().second
process = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True, preexec_fn=os.setsid)
running_time = 0
while process.poll() is None and running_time < timeout:
time_now = datetime.datetime.now().second
running_time = int(time_now - time_start)
time.sleep(3)
if process.poll() is None:
process.terminate()
time.sleep(3)
if process.poll() is None:
process.kill()
stdout, stderr = process.communicate()
if not stderr:
stderr = ''
if not stdout:
stdout = ''
if stderr and stderr != '':
stdout += " Error: " + stderr
if process:
returncode = process.returncode
else:
returncode = 1
if returncode != 1 and 'Command time-out' in stdout:
returncode = 1
if returncode is None:
returncode = 0
return returncode, stdout
示例14: check_output_group_kill
# 需要导入模块: import os [as 别名]
# 或者: from os import setsid [as 别名]
def check_output_group_kill(*popenargs, timeout=None, **kwargs):
"""
Custom check_output implementation that kill the whole process tree instead of
simply it's head.
Idea taken from
https://stackoverflow.com/questions/36952245/subprocess-timeout-failure
"""
if "stdout" in kwargs:
raise ValueError("stdout argument not allowed, it will be overridden.")
input = "" if kwargs.get("universal_newlines", False) else b""
kwargs["stdin"] = PIPE
with Popen(*popenargs, **kwargs, stdout=PIPE, preexec_fn=os.setsid) as process:
try:
stdout, stderr = process.communicate(input, timeout=timeout)
except TimeoutExpired:
process.kill()
os.killpg(process.pid, signal.SIGKILL) # send signal to the process group
stdout, stderr = process.communicate()
raise TimeoutExpired(process.args, timeout, output=stdout, stderr=stderr)
except:
process.kill()
process.wait()
raise
retcode = process.poll()
if retcode:
raise CalledProcessError(
retcode, process.args, output=stdout, stderr=stderr
)
return CompletedProcess(process.args, retcode, stdout, stderr)
示例15: __init__
# 需要导入模块: import os [as 别名]
# 或者: from os import setsid [as 别名]
def __init__(self, height):
super(Terminal, self).__init__(height, line_wrap=True, parser=AnsiTerminalParser())
#Key definitions
self._map = {}
for k, v in [
(Screen.KEY_LEFT, "kcub1"),
(Screen.KEY_RIGHT, "kcuf1"),
(Screen.KEY_UP, "kcuu1"),
(Screen.KEY_DOWN, "kcud1"),
(Screen.KEY_HOME, "khome"),
(Screen.KEY_END, "kend"),
(Screen.KEY_BACK, "kbs"),
]:
self._map[k] = curses.tigetstr(v)
self._map[Screen.KEY_TAB] = "\t".encode()
# Open a pseudo TTY to control the interactive session. Make it non-blocking.
self._master, slave = pty.openpty()
fl = fcntl.fcntl(self._master, fcntl.F_GETFL)
fcntl.fcntl(self._master, fcntl.F_SETFL, fl | os.O_NONBLOCK)
# Start the shell and thread to pull data from it.
self._shell = subprocess.Popen(["bash", "-i"], preexec_fn=os.setsid, stdin=slave, stdout=slave, stderr=slave)
self._lock = threading.Lock()
self._thread = threading.Thread(target=self._background)
self._thread.daemon = True
self._thread.start()