python类setsid()的实例源码

test_transform_service.py 文件源码 项目:monasca-transform 作者: openstack 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
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
test_functional.py 文件源码 项目:cotyledon 作者: sileht 项目源码 文件源码 阅读 31 收藏 0 点赞 0 评论 0
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)
process_controller.py 文件源码 项目:SublimeTerm 作者: percevalw 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
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)
SoloMapper.py 文件源码 项目:Solo-Mapper 作者: Escadrone 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
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
_twistd_unix.py 文件源码 项目:hostapd-mana 作者: adde88 项目源码 文件源码 阅读 30 收藏 0 点赞 0 评论 0
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)
conch.py 文件源码 项目:hostapd-mana 作者: adde88 项目源码 文件源码 阅读 39 收藏 0 点赞 0 评论 0
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
proxy.py 文件源码 项目:sshaolin 作者: bucknerns 项目源码 文件源码 阅读 41 收藏 0 点赞 0 评论 0
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)
generator.py 文件源码 项目:OSPTF 作者: xSploited 项目源码 文件源码 阅读 36 收藏 0 点赞 0 评论 0
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)
        """)
worker.py 文件源码 项目:corvus-web-public 作者: eleme 项目源码 文件源码 阅读 31 收藏 0 点赞 0 评论 0
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)
tools.py 文件源码 项目:Dallinger 作者: Dallinger 项目源码 文件源码 阅读 32 收藏 0 点赞 0 评论 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
daemonizer.py 文件源码 项目:SameKeyProxy 作者: xzhou 项目源码 文件源码 阅读 73 收藏 0 点赞 0 评论 0
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
sifter.py 文件源码 项目:sandsifter 作者: xoreaxeaxeax 项目源码 文件源码 阅读 38 收藏 0 点赞 0 评论 0
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
            )
master.py 文件源码 项目:mitogen 作者: dw 项目源码 文件源码 阅读 34 收藏 0 点赞 0 评论 0
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
client_tests.py 文件源码 项目:bandit-http-server 作者: evancasey 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
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()
generator.py 文件源码 项目:pupy 作者: ru-faraon 项目源码 文件源码 阅读 51 收藏 0 点赞 0 评论 0
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)
        """)
cmd_run.py 文件源码 项目:relaax 作者: deeplearninc 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
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)
fdsl_client.py 文件源码 项目:fdslight 作者: fdslight 项目源码 文件源码 阅读 32 收藏 0 点赞 0 评论 0
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()
fdsl_server.py 文件源码 项目:fdslight 作者: fdslight 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
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()
scheduler.py 文件源码 项目:spc 作者: whbrewer 项目源码 文件源码 阅读 34 收藏 0 点赞 0 评论 0
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()
monast.py 文件源码 项目:monast 作者: dagmoller 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
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
##
watchdog.py 文件源码 项目:landscape-client 作者: CanonicalLtd 项目源码 文件源码 阅读 30 收藏 0 点赞 0 评论 0
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)
dropbox.py 文件源码 项目:dotfiles 作者: nfischer 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
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
video_recorder.py 文件源码 项目:gym 作者: openai 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
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)
process.py 文件源码 项目:clusterfuzz-tools 作者: google 项目源码 文件源码 阅读 32 收藏 0 点赞 0 评论 0
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
process_test.py 文件源码 项目:clusterfuzz-tools 作者: google 项目源码 文件源码 阅读 34 收藏 0 点赞 0 评论 0
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()
process_test.py 文件源码 项目:clusterfuzz-tools 作者: google 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
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()
process_test.py 文件源码 项目:clusterfuzz-tools 作者: google 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
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()
common.py 文件源码 项目:clusterfuzz-tools 作者: google 项目源码 文件源码 阅读 33 收藏 0 点赞 0 评论 0
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)
zynthian_engine.py 文件源码 项目:zynthian-ui 作者: zynthian 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
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()
_twistd_unix.py 文件源码 项目:sslstrip-hsts-openwrt 作者: adde88 项目源码 文件源码 阅读 46 收藏 0 点赞 0 评论 0
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)


问题


面经


文章

微信
公众号

扫码关注公众号