Python os._exit() Examples

The following are code examples for showing how to use os._exit(). They are extracted from open source Python projects. You can vote up the examples you like or vote down the ones you don't like. You can also save this page to your account.

Example 1
Project: monasca-transform   Author: openstack   File: test_transform_service.py    (Apache License 2.0) View Source Project 8 votes vote down vote up
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 
Example 2
Project: Python   Author: Guzi219   File: qiushimm.py    (license) View Source Project 7 votes vote down vote up
def ShowOnePage(self, now_page_items, page):
        for idx, item in enumerate(now_page_items):
            print "\ndownload " + item[1]
            self.saveFile(item[0], page, idx)
        #print '========one page done.================='
        print '========Please hit the Enter.================='
        if self.unload_page_num == page:
            print '========all pages done. clean the repeated files.=========='
            self.CleanRepeatImage() #at last, deal with the repeated images.
            print 'Nothing left. Now close this application.'
            # self.enable = False  #let the main thread know it's time to quit
            os._exit(0) #can teminal main thread.

        # ???????
        time.sleep(1)
        print 'take a snap for 1s.'
        # myInput = raw_input()
        # if myInput == ":q":
        #     self.CleanRepeatImage() #if break manually, must clean work dir.
        #     self.enable = False

    # deal with the repeated image 
Example 3
Project: spoon   Author: SpamExperts   File: server.py    (GNU General Public License v2.0) View Source Project 7 votes vote down vote up
def serve_forever(self, poll_interval=0.1):
        """Fork the current process and wait for all children to finish."""
        if self.prefork is None or self.prefork <= 1:
            return super(_SporkMixIn, self).serve_forever(
                poll_interval=poll_interval)
        pids = []
        for dummy in range(self.prefork):
            pid = os.fork()
            if not pid:
                super(_SporkMixIn, self).serve_forever(
                    poll_interval=poll_interval)
                os._exit(0)
            else:
                self.log.info("Forked worker %s", pid)
                pids.append(pid)
        self.pids = pids
        for pid in self.pids:
            _eintr_retry(os.waitpid, pid, 0) 
Example 4
Project: data_pipeline   Author: Yelp   File: copy_table_to_blackhole_table.py    (license) View Source Project 6 votes vote down vote up
def run(self):
        self.log.info("Python Version: {}".format(sys.version_info))
        is_success = True
        try:
            self.initial_action()
            self.process_table()
            self.log_info()
        except SystemExit:
            pass
        except Exception:
            if self.refresh_id:
                self.schematizer.update_refresh(
                    self.refresh_id,
                    RefreshStatus.FAILED,
                    self.processed_row_count
                )
            # Sends an email containing the exception encountered.
            self._email_exception_in_exception_context()
            is_success = False
        finally:
            # We don't want to drop the blackhole table until the replication handler is using
            # the schema_tracker database stably. (TODO: DATAPIPE-845)
            # self.final_action()
            if not is_success:
                os._exit(1) 
Example 5
Project: kinect-2-libras   Author: inessadl   File: SocketServer.py    (Apache License 2.0) View Source Project 6 votes vote down vote up
def process_request(self, request, client_address):
        """Fork a new subprocess to process the request."""
        self.collect_children()
        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) #close handle in parent process
            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) 
Example 6
Project: anonymine   Author: oskar-skog   File: configure.py    (license) View Source Project 6 votes vote down vote up
def myexit(code):
    '''
    Substitute for sys.exit.  MUST be used at EOF.
    
    This wrapper flushes output and calls `os._exit`.
    
    Python 2.7.10 on NetBSD 6.1 x86-32 has a bug that causes the
    interpreter to hang after the program has finished if it has ever
    called `subprocess.Popen`.  All of `exit`, `sys.exit`, `quit` and
    end of file are affected.
    
    Using `os._exit` won't work either because output is buffered and
    not flushed on exit.
    
    https://github.com/oskar-skog/anonymine/issues/7
    http://bugs.python.org/issue28807
    http://gnats.netbsd.org/cgi-bin/query-pr-single.pl?number=51657
    '''
    sys.stdout.flush()
    sys.stderr.flush()
    os._exit(code) 
Example 7
Project: ave   Author: sonyxperiadev   File: stress.py    (BSD 3-Clause "New" or "Revised" License) View Source Project 6 votes vote down vote up
def client_03(port, prefix):
    c = RemoteControl(('',port), None, timeout=10)
    while True:
        if random.random() > 0.7:
            c = RemoteControl(('',port), None, timeout=10)
        try:
            c.raise_ave_exception({'message':'hello', 'recognize':'me'})
        except Exit:
            os._exit(0)
        except AveException, e:
            if 'recognize' in e.details:
                continue
            print('client PID=%d got exception: %s' % (os.getpid(), e))
            os._exit(2)
        except Exception, e:
            print('client PID=%d got exception: %s' % (os.getpid(), e))
            os._exit(1)

# load test for control. send hickup if the control freezes up 
Example 8
Project: ave   Author: sonyxperiadev   File: config.py    (BSD 3-Clause "New" or "Revised" License) View Source Project 6 votes vote down vote up
def t07(w):
    pretty = '%s t7' % __file__
    print(pretty)

    base = os.path.join(w.path, '.ave', 'config')
    os.makedirs(base)

    try:
        authkeys = ave.config.load_authkeys(w.path)
        print('FAIL %s: could load invalid config: %s' % (pretty, authkeys))
        return False
    except Exception, e:
        name = ave.pwd.getpwuid_name(os.getuid())
        if 'run "ave-config --bootstrap=%s"' % name not in unicode(e):
            print('FAIL %s: wrong error: %s' % (pretty, e))
            return False

    return True

# used by t8-t10. calls os._exit() so only use from within child process. 
Example 9
Project: ave   Author: sonyxperiadev   File: config.py    (BSD 3-Clause "New" or "Revised" License) View Source Project 6 votes vote down vote up
def check_fds(pretty, dump, ref):
    # check that 0-2 are the stdio file descriptors. i.e. that they are
    # connected to pseudo terminals.
    for i in range(3):
         if not dump[i].startswith('/dev/pts'):
             print('FAIL %s: wrong stdio file at %d: %s' % (pretty, i, dump[i]))
             os._exit(2)

    # any file descriptors in the range [3..max(all fds)] must be files that
    # were opened by this process. for this test we expect all of them to point
    # to the same file (the current .py file). otherwise they are not intact.
    if max(dump.keys()) <= 2:
        os._exit(0) # all OK
    for i in range(3, max(ref.keys())): # check that all ref keys are intact
        if not dump[i] == ref[i]:
            print('FAIL %s: clobbered fd at %d: %s' % (pretty, i, dump[i]))
            os._exit(5)

# check if ave.config.load_etc() clobbers file descriptors. this is a bug in
# winbindd which is used by PAM to implement a backend for Python's pwd module.
# we *have* to use the pwd module, so the global side effect (clobbering a file
# descriptor) must be hidden from the caller. 
Example 10
Project: ave   Author: sonyxperiadev   File: control.py    (BSD 3-Clause "New" or "Revised" License) View Source Project 6 votes vote down vote up
def shutdown(self, details=None):
        '''
        Exit the main loop and write a last exit message on all connections
        before closing them. The exit message will be serialized as an ``Exit``
        exception.
        '''
        # close all open connections
        for connection in self.accepting:
            connection.close()
        for connection in self.authenticating:
            if details:
                self.write_exit_message(connection, details)
            connection.close()
        for connection in self.established:
            if details:
                self.write_exit_message(connection, details)
            connection.close()
        if self.listener:
            self.listener.close()
        self.join_deferred()
        os._exit(1) # causes queued messages on outbound sockets to be flushed
                    # in the background. Man page: socket(7) SO_LINGER 
Example 11
Project: ave   Author: sonyxperiadev   File: config.py    (BSD 3-Clause "New" or "Revised" License) View Source Project 6 votes vote down vote up
def t07(w):
    pretty = '%s t7' % __file__
    print(pretty)

    base = os.path.join(w.path, '.ave', 'config')
    os.makedirs(base)

    try:
        authkeys = ave.config.load_authkeys(w.path)
        print('FAIL %s: could load invalid config: %s' % (pretty, authkeys))
        return False
    except Exception, e:
        name = ave.pwd.getpwuid_name(os.getuid())
        if 'run "ave-config --bootstrap=%s"' % name not in unicode(e):
            print('FAIL %s: wrong error: %s' % (pretty, e))
            return False

    return True

# used by t8-t10. calls os._exit() so only use from within child process. 
Example 12
Project: ave   Author: sonyxperiadev   File: config.py    (BSD 3-Clause "New" or "Revised" License) View Source Project 6 votes vote down vote up
def check_fds(pretty, dump, ref):
    # check that 0-2 are the stdio file descriptors. i.e. that they are
    # connected to pseudo terminals.
    for i in range(3):
         if not dump[i].startswith('/dev/pts'):
             print('FAIL %s: wrong stdio file at %d: %s' % (pretty, i, dump[i]))
             os._exit(2)

    # any file descriptors in the range [3..max(all fds)] must be files that
    # were opened by this process. for this test we expect all of them to point
    # to the same file (the current .py file). otherwise they are not intact.
    if max(dump.keys()) <= 2:
        os._exit(0) # all OK
    for i in range(3, max(ref.keys())): # check that all ref keys are intact
        if not dump[i] == ref[i]:
            print('FAIL %s: clobbered fd at %d: %s' % (pretty, i, dump[i]))
            os._exit(5)

# check if ave.config.load_etc() clobbers file descriptors. this is a bug in
# winbindd which is used by PAM to implement a backend for Python's pwd module.
# we *have* to use the pwd module, so the global side effect (clobbering a file
# descriptor) must be hidden from the caller. 
Example 13
Project: ave   Author: sonyxperiadev   File: control.py    (BSD 3-Clause "New" or "Revised" License) View Source Project 6 votes vote down vote up
def shutdown(self, details=None):
        '''
        Exit the main loop and write a last exit message on all connections
        before closing them. The exit message will be serialized as an ``Exit``
        exception.
        '''
        # close all open connections
        for connection in self.accepting:
            connection.close()
        for connection in self.authenticating:
            if details:
                self.write_exit_message(connection, details)
            connection.close()
        for connection in self.established:
            if details:
                self.write_exit_message(connection, details)
            connection.close()
        if self.listener:
            self.listener.close()
        self.join_deferred()
        os._exit(1) # causes queued messages on outbound sockets to be flushed
                    # in the background. Man page: socket(7) SO_LINGER 
Example 14
Project: hostapd-mana   Author: adde88   File: SocketServer.py    (license) View Source Project 6 votes vote down vote up
def process_request(self, request, client_address):
        """Fork a new subprocess to process the request."""
        self.collect_children()
        pid = os.fork()
        if pid:
            # Parent process
            if self.active_children is None:
                self.active_children = set()
            self.active_children.add(pid)
            self.close_request(request) #close handle in parent process
            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) 
Example 15
Project: hostapd-mana   Author: adde88   File: _twistd_unix.py    (license) View Source Project 6 votes vote down vote up
def startLogging(logfilename, sysLog, prefix, nodaemon):
    if logfilename == '-':
        if not nodaemon:
            print 'daemons cannot log to stdout'
            os._exit(1)
        logFile = sys.stdout
    elif sysLog:
        syslog.startLogging(prefix)
    elif nodaemon and not logfilename:
        logFile = sys.stdout
    else:
        logFile = app.getLogFile(logfilename or 'twistd.log')
        try:
            import signal
        except ImportError:
            pass
        else:
            def rotateLog(signal, frame):
                from twisted.internet import reactor
                reactor.callFromThread(logFile.rotate)
            signal.signal(signal.SIGUSR1, rotateLog)
        
    if not sysLog:
        log.startLogging(logFile)
    sys.stdout.flush() 
Example 16
Project: hostapd-mana   Author: adde88   File: _twistd_unix.py    (license) View Source Project 6 votes vote down vote up
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) 
Example 17
Project: hostapd-mana   Author: adde88   File: app.py    (license) View Source Project 6 votes vote down vote up
def fixPdb():
    def do_stop(self, arg):
        self.clear_all_breaks()
        self.set_continue()
        from twisted.internet import reactor
        reactor.callLater(0, reactor.stop)
        return 1

    def help_stop(self):
        print """stop - Continue execution, then cleanly shutdown the twisted reactor."""
    
    def set_quit(self):
        os._exit(0)

    pdb.Pdb.set_quit = set_quit
    pdb.Pdb.do_stop = do_stop
    pdb.Pdb.help_stop = help_stop 
Example 18
Project: hostapd-mana   Author: adde88   File: conch.py    (license) View Source Project 6 votes vote down vote up
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 
Example 19
Project: sc-controller   Author: kozec   File: autoswitcher.py    (license) View Source Project 6 votes vote down vote up
def on_sa_profile(self, mapper, action):
		profile_name = action.profile
		path = find_profile(profile_name)
		if path:
			with self.lock:
				if path != self.current_profile and not self.current_profile.endswith(".mod"):
					# Switch only if target profile is not active
					# and active profile is not being editted.
					try:
						if self.config['autoswitch_osd']:
							msg = (_("Switched to profile") + " " + profile_name)
							self.socket.send(b"OSD: " + msg.encode('utf-8') + b"\n")
						self.socket.send(b"Profile: " + path.encode('utf-8') + b"\n")
					except:
						log.error("Socket write failed")
						os._exit(2)
						return
		else:
			log.error("Cannot switch to profile '%s', profile file not found", self.conds[c]) 
Example 20
Project: esys-pbi   Author: fsxfreak   File: experiment.py    (license) View Source Project 6 votes vote down vote up
def stop(stimuli, bci, graph, bci_queue, pupil=None):
  print('Terminating from the main thread...')
  #termination handling for windows
  event.set()
  while True:
    if bci_queue is None or bci_queue.get() == 'SAVED_BCI' or os.name != 'nt':
    #(in windows) 'SAVED_BCI' ensures data has saved before process termination
      try:
        stimuli.terminate()
        bci.terminate()
        graph.terminate()
        os._exit(0)
      except AttributeError:
        pass
      break

  if pupil:
    pupil.terminate() 
Example 21
Project: rubber-docker   Author: Fewbytes   File: rd.py    (license) View Source Project 6 votes vote down vote up
def run(command):
    # TODO: replace this with fork()
    #       (https://docs.python.org/2/library/os.html#os.fork)
    pid = 0
    if pid == 0:
        # This is the child, we'll try to do some containment here
        try:
            contain(command)
        except Exception:
            traceback.print_exc()
            os._exit(1)  # something went wrong in contain()

    # This is the parent, pid contains the PID of the forked process
    # wait for the forked child and fetch the exit status
    _, status = os.waitpid(pid, 0)
    print('{} exited with status {}'.format(pid, status)) 
Example 22
Project: rubber-docker   Author: Fewbytes   File: rd.py    (license) View Source Project 6 votes vote down vote up
def run(image_name, image_dir, container_dir, command):
    container_id = str(uuid.uuid4())

    pid = os.fork()
    if pid == 0:
        # This is the child, we'll try to do some containment here
        try:
            contain(command, image_name, image_dir, container_id,
                    container_dir)
        except Exception:
            traceback.print_exc()
            os._exit(1)  # something went wrong in contain()

    # This is the parent, pid contains the PID of the forked process
    # wait for the forked child, fetch the exit status
    _, status = os.waitpid(pid, 0)
    print('{} exited with status {}'.format(pid, status)) 
Example 23
Project: rubber-docker   Author: Fewbytes   File: rd.py    (license) View Source Project 6 votes vote down vote up
def run(image_name, image_dir, container_dir, command):
    container_id = str(uuid.uuid4())
    pid = os.fork()
    if pid == 0:
        # This is the child, we'll try to do some containment here
        try:
            contain(command, image_name, image_dir, container_id,
                    container_dir)
        except Exception:
            traceback.print_exc()
            os._exit(1)  # something went wrong in contain()

    # This is the parent, pid contains the PID of the forked process
    # wait for the forked child, fetch the exit status
    _, status = os.waitpid(pid, 0)
    print('{} exited with status {}'.format(pid, status)) 
Example 24
Project: rubber-docker   Author: Fewbytes   File: rd.py    (license) View Source Project 6 votes vote down vote up
def run(image_name, image_dir, container_dir, command):
    container_id = str(uuid.uuid4())

    pid = os.fork()
    if pid == 0:
        # This is the child, we'll try to do some containment here
        try:
            contain(command, image_name, image_dir, container_id,
                    container_dir)
        except Exception:
            traceback.print_exc()
            os._exit(1)  # something went wrong in contain()

    # This is the parent, pid contains the PID of the forked process
    # wait for the forked child, fetch the exit status
    _, status = os.waitpid(pid, 0)
    print('{} exited with status {}'.format(pid, status)) 
Example 25
Project: rubber-docker   Author: Fewbytes   File: rd.py    (license) View Source Project 6 votes vote down vote up
def run(image_name, image_dir, container_dir, command):
    container_id = str(uuid.uuid4())

    pid = os.fork()
    if pid == 0:
        # This is the child, we'll try to do some containment here
        try:
            contain(command, image_name, image_dir, container_id, container_dir)
        except Exception:
            traceback.print_exc()
            os._exit(1)  # something went wrong in contain()

    # This is the parent, pid contains the PID of the forked process
    # wait for the forked child, fetch the exit status
    _, status = os.waitpid(pid, 0)
    print('{} exited with status {}'.format(pid, status)) 
Example 26
Project: rubber-docker   Author: Fewbytes   File: rd.py    (license) View Source Project 6 votes vote down vote up
def run(image_name, image_dir, container_dir, command):
    container_id = str(uuid.uuid4())

    # TODO: Switching to a new PID namespace (using unshare) would only affect
    #       the children of a process (because we can't change the PID of a
    #       running process), so we'll have to unshare here OR replace
    #       os.fork() with linux.clone()

    pid = os.fork()
    if pid == 0:
        # This is the child, we'll try to do some containment here
        try:
            contain(command, image_name, image_dir, container_id,
                    container_dir)
        except Exception:
            traceback.print_exc()
            os._exit(1)  # something went wrong in contain()

    # This is the parent, pid contains the PID of the forked process
    # wait for the forked child, fetch the exit status
    _, status = os.waitpid(pid, 0)
    print('{} exited with status {}'.format(pid, status)) 
Example 27
Project: vmx-docker-lwaftr   Author: Juniper   File: rpc-jet.py    (license) View Source Project 6 votes vote down vote up
def main(argv):
    """
    Used to fetch the snabb instance information from the JET app.

    :param argv: Arguments for the command
    :return: Dictionary of instances state information
    """
    try:
        # log device initialized successfully
        print "Device initialized for the configuration updates"
        #Start a thread to do the polling
        t = Thread(target=poll_snabb)
        t.daemon = True
        t.start()
        opw = OpServer()
        server.register_instance(opw)
        print ("Starting the reactor")
        server.serve_forever()

    except Exception as e:
        # log device initialization failed
        print("JET app exiting due to exception: %s" %str(e.message))
        os._exit(0)
    return 
Example 28
Project: kcli   Author: karmab   File: cli.py    (license) View Source Project 6 votes vote down vote up
def info(args):
    """Get info on vm"""
    names = args.names
    output = args.output
    fields = args.fields
    values = args.values
    lastvm = "%s/.kcli/vm" % os.environ.get('HOME')
    if not names:
        if os.path.exists(lastvm) and os.stat(lastvm).st_size > 0:
            names = [open(lastvm).readlines()[0].strip()]
            common.pprint("Using %s as vm" % names[0], color='green')
        else:
            common.pprint("Missing Vm's name", color='red')
            return
    global config
    k = config.k
    codes = []
    for name in names:
        result = k.info(name, output=output, fields=fields, values=values)
        code = common.handle_response(result, name, quiet=True)
        codes.append(code)
    os._exit(1 if 1 in codes else 0) 
Example 29
Project: kcli   Author: karmab   File: cli.py    (license) View Source Project 6 votes vote down vote up
def disk(args):
    """Add/Delete disk of vm"""
    name = args.name
    delete = args.delete
    size = args.size
    diskname = args.diskname
    template = args.template
    pool = args.pool
    global config
    k = config.k
    if delete:
        if diskname is None:
            common.pprint("Missing diskname. Leaving...", color='red')
            os._exit(1)
        common.pprint("Deleting disk %s from %s..." % (diskname, name), color='green')
        k.delete_disk(name, diskname)
        return
    if size is None:
        common.pprint("Missing size. Leaving...", color='red')
        os._exit(1)
    if pool is None:
        common.pprint("Missing pool. Leaving...", color='red')
        os._exit(1)
    common.pprint("Adding disk to %s..." % (name), color='green')
    k.add_disk(name=name, size=size, pool=pool, template=template) 
Example 30
Project: kcli   Author: karmab   File: cli.py    (license) View Source Project 6 votes vote down vote up
def pool(args):
    """Create/Delete pool"""
    pool = args.pool
    delete = args.delete
    full = args.delete
    pooltype = args.pooltype
    path = args.path
    global config
    k = config.k
    if delete:
        common.pprint("Deleting pool %s..." % (pool), color='green')
        k.delete_pool(name=pool, full=full)
        return
    if path is None:
        common.pprint("Missing path. Leaving...", color='red')
        os._exit(1)
    common.pprint("Adding pool %s..." % (pool), color='green')
    k.create_pool(name=pool, poolpath=path, pooltype=pooltype) 
Example 31
Project: kcli   Author: karmab   File: cli.py    (license) View Source Project 6 votes vote down vote up
def network(args):
    """Create/Delete/List Network"""
    name = args.name
    delete = args.delete
    isolated = args.isolated
    cidr = args.cidr
    nodhcp = args.nodhcp
    domain = args.domain
    pxe = args.pxe
    global config
    k = config.k
    if name is None:
        common.pprint("Missing Network", color='red')
        os._exit(1)
    if delete:
        result = k.delete_network(name=name)
        common.handle_response(result, name, element='Network ', action='deleted')
    else:
        if isolated:
            nat = False
        else:
            nat = True
        dhcp = not nodhcp
        result = k.create_network(name=name, cidr=cidr, dhcp=dhcp, nat=nat, domain=domain, pxe=pxe)
        common.handle_response(result, name, element='Network ') 
Example 32
Project: weibo   Author: windskyer   File: manager.py    (license) View Source Project 6 votes vote down vote up
def init_host(self, tg, **kwargs):
        LOG.info(_LI('Willing init  host function.......'))
        if CONF.is_all:
            pid = os.fork()
            if pid == 0:
                child_started = False
                while True:
                    enable_spawn = kwargs.get('enable_spawn', True)
                    if enable_spawn:
                        eventlet.spawn(self.get_all_user_all_weibo_info,
                                       **kwargs)
                        child_started = True
                    else:
                        kwargs['tg'] = tg
                        self.get_all_user_all_weibo_info(**kwargs)
                        child_started = True
                    if not child_started:
                        break
                os._exit(2)

            LOG.debug(_LI('Started child %d' % pid))

    # ?????? 14400s  ????4? 
Example 33
Project: OSPTF   Author: xSploited   File: generator.py    (license) View Source Project 6 votes vote down vote up
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)
        """) 
Example 34
Project: iotronic-lightning-rod   Author: openstack   File: Board.py    (license) View Source Project 6 votes vote down vote up
def getWampAgent(self, config):
        '''This method gets and sets the WAMP Board attributes from the conf file.

        '''
        try:

            self.wamp_config = config['iotronic']['wamp']['main-agent']
            LOG.info('WAMP Agent settings:')

        except Exception:
            if (self.status is None) | (self.status == "registered"):
                self.wamp_config = \
                    config['iotronic']['wamp']['registration-agent']
                LOG.info('Registration Agent settings:')
            else:
                LOG.error(
                    "WAMP Agent configuration is wrong... "
                    "please check settings.json WAMP configuration... Bye!"
                )
                os._exit(1)

        LOG.info(' - agent: ' + str(self.agent))
        LOG.info(' - url: ' + str(self.wamp_config['url']))
        LOG.info(' - realm: ' + str(self.wamp_config['realm']))
        # LOG.debug("- conf:\n" + json.dumps(self.wamp_config, indent=4)) 
Example 35
Project: corvus-web-public   Author: eleme   File: worker.py    (license) View Source Project 6 votes vote down vote up
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) 
Example 36
Project: masakari-monitors   Author: openstack   File: host.py    (license) View Source Project 6 votes vote down vote up
def init_host(self):
        """Initialization for hostmonitor."""
        try:
            # Determine dynamic load driver from configuration.
            driver_name = CONF.host.monitoring_driver

            # Load the driver to global.
            self.driver = driver.DriverManager(
                namespace='hostmonitor.driver',
                name=driver_name,
                invoke_on_load=True,
                invoke_args=(),
            )
        except Exception as e:
            LOG.exception(
                "Exception caught during initializing hostmonitor: %s", e)
            os._exit(1) 
Example 37
Project: 163mooc_dumper   Author: wsdzl   File: 163down.py    (license) View Source Project 6 votes vote down vote up
def main():
	if len(sys.argv) == 1:
		if os.path.isfile('tmp_url.txt'):
			with open('tmp_url.txt') as f:
				url = f.read()
		else:
			url = input('URL: ')
	else:
		url = sys.argv[1]
	with open('tmp_url.txt', 'w') as f:
		f.write(url)
	name, videos = parse_videos(url)
	length = len(videos)
	if not os.path.isdir(name): os.makedirs(name)
	for i in range(length):
		try:
			download(videos, i, name, length)
		except KeyboardInterrupt:
			os._exit(1)
	if os.path.isfile('tmp_url.txt'):
		os.unlink('tmp_url.txt') 
Example 38
Project: SameKeyProxy   Author: xzhou   File: daemonizer.py    (license) View Source Project 6 votes vote down vote up
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 
Example 39
Project: Airscript-ng   Author: Sh3llcod3   File: airscript-old-stable.py    (license) View Source Project 6 votes vote down vote up
def update_this_script():
    check_depends()
    import subprocess,os
    while True:
        up_choc = input("\n%sUpdate this script? Any local changes will be lost! y/n > " %(col.endl))
        if up_choc.lower().startswith("y"):
            status_code_update = subprocess.call("git stash && git pull",shell=True)
            print("Update is done. Relaunch!")
            if status_code_update != 0:
                while True:
                    fix_git_config_rand = input("See something to do with %sgit-config%s? Fix that? %sy%s/%sn%s> " %(col.blue_deep,col.endl,col.okg,col.endl,col.warn,col.endl))
                    if fix_git_config_rand.lower().startswith("y"):
                        find_out = subprocess.check_output
                        user_git_name = find_out("id -u -n",shell=True).decode("utf-8").rstrip()
                        user_git_hostname = find_out("uname -n",shell=True).decode("utf-8").rstrip()
                        subprocess.call("git config user.email \"%[email protected]%s.com\" "  %(user_git_name,user_git_hostname),shell=True)
                        subprocess.call("git config user.name \"%s\" " %(user_git_name),shell=True)
                        print("Applied fix, pulling update...")
                        subprocess.call("git stash && git pull",shell=True)
                        break
                    elif fix_git_config_rand.lower().startswith("n"):
                        break
            os._exit(1)
        elif up_choc.lower().startswith("n"):
            title() 
Example 40
Project: Airscript-ng   Author: Sh3llcod3   File: no-color-airscript-ng.py    (license) View Source Project 6 votes vote down vote up
def update_this_script():
    check_depends()
    import subprocess,os
    while True:
        up_choc = input("\n%sUpdate this script? Any local changes will be lost! y/n > " %(col.endl))
        if up_choc.lower().startswith("y"):
            status_code_update = subprocess.call("git stash && git pull",shell=True)
            print("Update is done. Relaunch!")
            if status_code_update != 0:
                while True:
                    fix_git_config_rand = input("See something to do with %sgit-config%s? Fix that? %sy%s/%sn%s> " %(col.blue_deep,col.endl,col.okg,col.endl,col.warn,col.endl))
                    if fix_git_config_rand.lower().startswith("y"):
                        find_out = subprocess.check_output
                        user_git_name = find_out("id -u -n",shell=True).decode("utf-8").rstrip()
                        user_git_hostname = find_out("uname -n",shell=True).decode("utf-8").rstrip()
                        subprocess.call("git config user.email \"%[email protected]%s.com\" "  %(user_git_name,user_git_hostname),shell=True)
                        subprocess.call("git config user.name \"%s\" " %(user_git_name),shell=True)
                        print("Applied fix, pulling update...")
                        subprocess.call("git stash && git pull",shell=True)
                        break
                    elif fix_git_config_rand.lower().startswith("n"):
                        break
            os._exit(1)
        elif up_choc.lower().startswith("n"):
            title() 
Example 41
Project: Airscript-ng   Author: Sh3llcod3   File: no-color-airscript-ng.py    (license) View Source Project 6 votes vote down vote up
def gitdeps():
    import subprocess
    call = subprocess.call
    if call("ls ~/.airscriptNG/air 2>/dev/null >/dev/null",shell=True) != 0:
        if call('/usr/bin/env ping -c1 8.8.8.8 >/dev/null 2>/dev/null',shell=True) == 0:
            call("mkdir -p ~/.airscriptNG/air && cd ~/.airscriptNG/air && apt update --allow-unauthenticated && apt install git git-core libnl-3-dev openssl libnl*-gen* libgcrypt20-dev build-essential libssl-dev -y --allow-unauthenticated && git clone git://git.kali.org/packages/aircrack-ng.git -b upstream && cd * && make gcrypt=true",shell=True)
        else:
            print('\n%s[-]%s Failed to install inital dependancies, please connect to the internet and try again\n' %(col.fail,col.endl))
            os._exit(1)
    if call("ls ~/.airscriptNG/wps 2>/dev/null >/dev/null",shell=True) != 0:
        if call('/usr/bin/env ping -c1 8.8.8.8 >/dev/null 2>/dev/null',shell=True) == 0:
            call("mkdir -p ~/.airscriptNG/wps && cd ~/.airscriptNG/wps && apt update --allow-unauthenticated && apt install libpcap-dev build-essential -y --allow-unauthenticated && git clone git://git.kali.org/packages/reaver.git -b upstream && cd */src && ./configure && make",shell=True)
        else:
            print('\n%s[-]%s Failed to install inital dependancies, please connect to the internet and try again\n' %(col.fail,col.endl))
            os._exit(1)
    if call("ls ~/.airscriptNG/magic 2>/dev/null >/dev/null",shell=True) != 0:
        if call('/usr/bin/env ping -c1 8.8.8.8 >/dev/null 2>/dev/null',shell=True) == 0:
            call("mkdir -p ~/.airscriptNG/magic && cd ~/.airscriptNG/magic && apt update --allow-unauthenticated && apt install libssl-dev build-essential -y --allow-unauthenticated && git clone git://git.kali.org/packages/pixiewps.git -b upstream && cd */src/ && make && make install",shell=True)
        else:
            print('\n%s[-]%s Failed to install inital dependancies, please connect to the internet and try again\n' %(col.fail,col.endl))
            os._exit(1) 
Example 42
Project: Airscript-ng   Author: Sh3llcod3   File: airscript-ng.py    (license) View Source Project 6 votes vote down vote up
def update_this_script():
    check_depends()
    import subprocess,os
    while True:
        up_choc = input("\n%sUpdate this script? Any local changes will be lost! y/n > " %(col.endl))
        if up_choc.lower().startswith("y"):
            status_code_update = subprocess.call("git stash && git pull",shell=True)
            print("Update is done. Relaunch!")
            if status_code_update != 0:
                while True:
                    fix_git_config_rand = input("See something to do with %sgit-config%s? Fix that? %sy%s/%sn%s> " %(col.blue_deep,col.endl,col.okg,col.endl,col.warn,col.endl))
                    if fix_git_config_rand.lower().startswith("y"):
                        find_out = subprocess.check_output
                        user_git_name = find_out("id -u -n",shell=True).decode("utf-8").rstrip()
                        user_git_hostname = find_out("uname -n",shell=True).decode("utf-8").rstrip()
                        subprocess.call("git config user.email \"%[email protected]%s.com\" "  %(user_git_name,user_git_hostname),shell=True)
                        subprocess.call("git config user.name \"%s\" " %(user_git_name),shell=True)
                        print("Applied fix, pulling update...")
                        subprocess.call("git stash && git pull",shell=True)
                        break
                    elif fix_git_config_rand.lower().startswith("n"):
                        break
            os._exit(1)
        elif up_choc.lower().startswith("n"):
            title() 
Example 43
Project: Airscript-ng   Author: Sh3llcod3   File: airscript-ng.py    (license) View Source Project 6 votes vote down vote up
def gitdeps():
    import subprocess
    call = subprocess.call
    if call("ls ~/.airscriptNG/air 2>/dev/null >/dev/null",shell=True) != 0:
        if call('/usr/bin/env ping -c1 8.8.8.8 >/dev/null 2>/dev/null',shell=True) == 0:
            call("mkdir -p ~/.airscriptNG/air && cd ~/.airscriptNG/air && apt update --allow-unauthenticated && apt install git git-core libnl-3-dev openssl libnl*-gen* libgcrypt20-dev build-essential libssl-dev -y --allow-unauthenticated && git clone git://git.kali.org/packages/aircrack-ng.git -b upstream && cd * && make gcrypt=true",shell=True)
        else:
            print('\n%s[-]%s Failed to install inital dependancies, please connect to the internet and try again\n' %(col.fail,col.endl))
            os._exit(1)
    if call("ls ~/.airscriptNG/wps 2>/dev/null >/dev/null",shell=True) != 0:
        if call('/usr/bin/env ping -c1 8.8.8.8 >/dev/null 2>/dev/null',shell=True) == 0:
            call("mkdir -p ~/.airscriptNG/wps && cd ~/.airscriptNG/wps && apt update --allow-unauthenticated && apt install libpcap-dev build-essential -y --allow-unauthenticated && git clone git://git.kali.org/packages/reaver.git -b upstream && cd */src && ./configure && make",shell=True)
        else:
            print('\n%s[-]%s Failed to install inital dependancies, please connect to the internet and try again\n' %(col.fail,col.endl))
            os._exit(1)
    if call("ls ~/.airscriptNG/magic 2>/dev/null >/dev/null",shell=True) != 0:
        if call('/usr/bin/env ping -c1 8.8.8.8 >/dev/null 2>/dev/null',shell=True) == 0:
            call("mkdir -p ~/.airscriptNG/magic && cd ~/.airscriptNG/magic && apt update --allow-unauthenticated && apt install libssl-dev build-essential -y --allow-unauthenticated && git clone git://git.kali.org/packages/pixiewps.git -b upstream && cd */src/ && make && make install",shell=True)
        else:
            print('\n%s[-]%s Failed to install inital dependancies, please connect to the internet and try again\n' %(col.fail,col.endl))
            os._exit(1) 
Example 44
Project: monasca-transform   Author: openstack   File: transform_service.py    (Apache License 2.0) View Source Project 5 votes vote down vote up
def shutdown_all_threads_and_die():
    """Shut down all threads and exit process.
    Hit it with a hammer to kill all threads and die.
    """
    LOG = log.getLogger(__name__)
    LOG.info('Monasca Transform service stopping...')
    os._exit(1) 
Example 45
Project: sipxecs-voicemail-transcription   Author: andrewsauder   File: libmilter.py    (MIT License) View Source Project 5 votes vote down vote up
def start(self):
        # Fork and run
        if not os.fork():
            self.run()
            os._exit(0)
        else:
            return 
Example 46
Project: Python   Author: Guzi219   File: qiushimm.py    (license) View Source Project 5 votes vote down vote up
def SaveTotalPageToFile(self, new_page_num):

        print '====================save the totalpage to totalpage.ini===================='

        file = INIFILE('totalpage.ini')

        # must write something if you set is_write to true. otherwise your file become empty.
        is_ok = file.Init(True, True)
        if not is_ok:
            print 'class initializing failed. check the [%s] file first.' % ('totalpage.ini')
            os._exit(0)

        old_page_num = file.GetValue('Main', 'totalpage')
        print '====================the old_page_num is [%s], the new_page_num is [%s]====================' % (old_page_num, new_page_num)
        file.SetValue('Main', 'totalpage', new_page_num)
        #close all
        file.UnInit()

        if int(new_page_num) >= int(old_page_num): #if there is new page
            self.unload_page_num = int(new_page_num) - int(old_page_num)
            if self.unload_page_num == 0:   #?????????????
               self.unload_page_num = 1
            elif self.unload_page_num > 0: #??????????????????????
                self.unload_page_num += 1
            print 'Ok, we got %s pages to load.' %(self.unload_page_num)
        else: #nothing new, stop main thread
            print 'Oops! Nothing new. exit main thread now.'
            os._exit(0) #terminal sub thread
            self.enable = False #terminal main thread

    # ???????? 
Example 47
Project: Python   Author: Guzi219   File: qiubaiadult.py    (license) View Source Project 5 votes vote down vote up
def SaveTotalPageToFile(self, new_page_num):

        print '====================save the totalpage to totalpage.ini===================='

        file = INIFILE('qiubaiadult_page.ini')

        # must write something if you set is_write to true. otherwise your file become empty.
        is_ok = file.Init(True, True)
        if not is_ok:
            print 'class initializing failed. check the [%s] file first.' % ('totalpage.ini')
            os._exit(0)

        old_page_num = file.GetValue('Main', 'totalpage')
        print '====================the old_page_num is [%s], the new_page_num is [%s]====================' % (old_page_num, new_page_num)
        file.SetValue('Main', 'totalpage', new_page_num)
        #close all
        file.UnInit()

        if int(new_page_num) >= int(old_page_num): #if there is new page
            # self.unload_page_num = int(new_page_num) - int(old_page_num)
            self.unload_page_num = int(new_page_num) - int(old_page_num)
            if self.unload_page_num == 0:   #?????????????
               self.unload_page_num = 1
            elif self.unload_page_num > 0: #??????????????????????***?????????
               self.unload_page_num += 1
            print 'since we start at page %s, we still got (%s-%s) pages to load.' %(self.page, self.unload_page_num, self.page)
        else: #nothing new, stop main thread
            print 'Oops! Nothing new. exit main thread now.'
            os._exit(0) #terminal sub thread
            self.enable = False #terminal main thread

    # ???????? 
Example 48
Project: amadash   Author: ipartola   File: daemon.py    (MIT License) View Source Project 5 votes vote down vote up
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()) 
Example 49
Project: amadash   Author: ipartola   File: detector.py    (MIT License) View Source Project 5 votes vote down vote up
def handle_button_traffic(self, mac, eth_protocol):
        button = self.buttons.get(mac)
        if not button:
            return

        now = time.time()
        time_delta = now - button['last_seen']
        button['last_seen'] = now
        if time_delta < options.main.button_timeout:
            return

        logging.getLogger().info('Button press detected: {} [{}].'.format(button['name'], button['mac']))
        action = button['action']
        env = dict(os.environ)
        env.update({
            'BUTTON_NAME': button['name'],
            'BUTTON_MAC': button['mac'],
        })

        pid = None
        try:
            pid = os.fork()
        except OSError as e:
            logging.getLogger().info("Could not fork for action: [{}] {}".format(e.errno, e.strerr))

        if pid == 0:
            daemonize(False)
            subprocess.Popen(action, shell=True, env=env).wait()
            os._exit(0) 
Example 50
Project: data_pipeline   Author: Yelp   File: copy_table_to_blackhole_table.py    (license) View Source Project 5 votes vote down vote up
def handle_interupt(self, signal, frame):
        self.schematizer.update_refresh(
            refresh_id=self.refresh_id,
            status=RefreshStatus.FAILED,
            offset=self.offset
        )
        os._exit(1)