A wrapper to start RQ worker as a new process.

    :param worker_instance: RQ's worker instance
    :param pid_path: A file to check if the worker
        is running or not
960645
def worker_wrapper(worker_instance, pid_path):
    
    def exit_handler(*args):
        """
        Remove pid file on exit
        """
        if len(args) > 0:
            print("Exit py signal {signal}".format(signal=args[0]))
        remove(pid_path)

    atexit.register(exit_handler)
    signal.signal(signal.SIGINT, exit_handler)
    signal.signal(signal.SIGTERM, exit_handler)

    worker_instance.work()

    # Remove pid file if the process can not catch signals
    exit_handler(2)
940214
def restart_process(self, pid):
        '''
        
        '''
        if self._restart_processes is False:
            return
        log.info(
            'Process %s (%s) died with exit status %s, restarting...',
            self._process_map[pid]['tgt'],
            pid,
            self._process_map[pid]['Process'].exitcode
        )
        # don't block, the process is already dead
        self._process_map[pid]['Process'].join(1)

        self.add_process(self._process_map[pid]['tgt'],
                         self._process_map[pid]['args'],
                         self._process_map[pid]['kwargs'])

        del self._process_map[pid]
1328689
def start

      unless @allow_multiple
        if running?
          log(:error, "\"#{@name}\" is already running (PID: #{@pid})")
          return
        end
      end

      @pid = fork do
        begin
          Process.setsid

          open(@pid_file, 'w') do |f|
            f << Process.pid
            @pid = Process.pid
          end

          execute_callback(:before_start)

          Dir.chdir @path.to_s
          File.umask 0000

          if @logger
            log = File.new(@log_file, "a")
            log.sync = @sync_log

            STDIN.reopen "/dev/null"
            STDOUT.reopen log
            STDERR.reopen STDOUT
          end

          trap("TERM") do
            stop
          end

          execute_callback(:start)

        rescue RuntimeError => message
          STDERR.puts message
          STDERR.puts message.backtrace

          execute_callback(:error)
        rescue => message
          STDERR.puts message
          STDERR.puts message.backtrace

          execute_callback(:error)
        end
      end

    rescue => message
      STDERR.puts message
      STDERR.puts message.backtrace
      execute_callback(:error)
    end
536895
def RunOnce(self):
    
    start_time = time.time()
    processed = 0

    queue_manager = queue_manager_lib.QueueManager(token=self.token)
    for queue in self.queues:
      # Freezeing the timestamp used by queue manager to query/delete
      # notifications to avoid possible race conditions.
      queue_manager.FreezeTimestamp()

      fetch_messages_start = time.time()
      notifications = queue_manager.GetNotifications(queue)
      stats_collector_instance.Get().RecordEvent(
          "worker_time_to_retrieve_notifications",
          time.time() - fetch_messages_start)

      stuck_flows = []
      for n in notifications:
        if n.in_progress:
          stuck_flows.append(n)

      # Process stuck flows first
      if stuck_flows:
        self.ProcessStuckFlows(stuck_flows, queue_manager)

      notifications_available = []
      for notification in notifications:
        # Filter out session ids we already tried to lock but failed.
        if notification.session_id not in self.queued_flows:
          notifications_available.append(notification)

      try:
        # If we spent too much time processing what we have so far, the
        # active_sessions list might not be current. We therefore break here
        # so we can re-fetch a more up to date version of the list, and try
        # again later. The risk with running with an old active_sessions list
        # is that another worker could have already processed this message,
        # and when we try to process it, there is nothing to do - costing us a
        # lot of processing time. This is a tradeoff between checking the data
        # store for current information and processing out of date
        # information.
        processed += self.ProcessMessages(
            notifications_available, queue_manager,
            self.RUN_ONCE_MAX_SECONDS - (time.time() - start_time))

      # We need to keep going no matter what.
      except Exception as e:  # pylint: disable=broad-except
        logging.error("Error processing message %s. %s.", e,
                      traceback.format_exc())
        stats_collector_instance.Get().IncrementCounter("grr_worker_exceptions")
        if flags.FLAGS.pdb_post_mortem:
          pdb.post_mortem()

      queue_manager.UnfreezeTimestamp()
      # If we have spent too much time, stop.
      if (time.time() - start_time) > self.RUN_ONCE_MAX_SECONDS:
        return processed
    return processed
1061069
def start(self):
        

        if self.run is True:
            self.job = multiprocessing.Process(target=self.indicator)
            self.job.start()
            return self.job
265097
def _run_parallel_process(self, start_path, stop_path, queue):
        
        process_num = int(current_process().name.split('-', 2)[1])
        self._run_process(start_path, stop_path, process_num)
        queue.put(self.consumer.put())
357241
def start(self):
        

        self._check_requirements()
        if not self.is_running():

            yield from self._library_check()

            try:
                self._rename_nvram_file()
            except OSError as e:
                raise IOUError("Could not rename nvram files: {}".format(e))

            iourc_path = self.iourc_path
            if not iourc_path:
                raise IOUError("Could not find an iourc file (IOU license)")
            if not os.path.isfile(iourc_path):
                raise IOUError("The iourc path '{}' is not a regular file".format(iourc_path))

            yield from self._check_iou_licence()
            yield from self._start_ubridge()

            self._create_netmap_config()
            if self.use_default_iou_values:
                # make sure we have the default nvram amount to correctly push the configs
                yield from self.update_default_iou_values()
            self._push_configs_to_nvram()

            # check if there is enough RAM to run
            self.check_available_ram(self.ram)

            self._nvram_watcher = FileWatcher(self._nvram_file(), self._nvram_changed, delay=2)

            # created a environment variable pointing to the iourc file.
            env = os.environ.copy()

            if "IOURC" not in os.environ:
                env["IOURC"] = iourc_path
            command = yield from self._build_command()
            try:
                log.info("Starting IOU: {}".format(command))
                self.command_line = ' '.join(command)
                self._iou_process = yield from asyncio.create_subprocess_exec(
                    *command,
                    stdout=asyncio.subprocess.PIPE,
                    stdin=asyncio.subprocess.PIPE,
                    stderr=subprocess.STDOUT,
                    cwd=self.working_dir,
                    env=env)
                log.info("IOU instance {} started PID={}".format(self._id, self._iou_process.pid))
                self._started = True
                self.status = "started"
                callback = functools.partial(self._termination_callback, "IOU")
                gns3server.utils.asyncio.monitor_process(self._iou_process, callback)
            except FileNotFoundError as e:
                raise IOUError("Could not start IOU: {}: 32-bit binary support is probably not installed".format(e))
            except (OSError, subprocess.SubprocessError) as e:
                iou_stdout = self.read_iou_stdout()
                log.error("Could not start IOU {}: {}\n{}".format(self._path, e, iou_stdout))
                raise IOUError("Could not start IOU {}: {}\n{}".format(self._path, e, iou_stdout))

            server = AsyncioTelnetServer(reader=self._iou_process.stdout, writer=self._iou_process.stdin, binary=True, echo=True)
            self._telnet_server = yield from asyncio.start_server(server.run, self._manager.port_manager.console_host, self.console)

            # configure networking support
            yield from self._networking()
511867
def run(self):
        
        from zengine.wf_daemon import run_workers, Worker

        worker_count = int(self.manager.args.workers or 1)
        if not self.manager.args.daemonize:
            print("Starting worker(s)")

        if worker_count > 1 or self.manager.args.autoreload:
            run_workers(worker_count,
                        self.manager.args.paths.split(' '),
                        self.manager.args.daemonize)
        else:
            worker = Worker()
            worker.run()
153892
def _run_path(self, path_num):
        
        # pre processing
        self.producer.initialize_path(path_num)
        self.consumer.initialize_path(path_num)

        # processing
        for new_date in self.grid:
            state = self.producer.evolve(new_date)
            self.consumer.consume(state)

        # post processing
        self.consumer.finalize_path(path_num)
492928
function() {
        //Default.
        var pathObj = new _( getPath('root') + '/tmp/pid/' );
        var path = pathObj.toString();

        //Create dir if needed.
        //console.debug("MKDIR  pathObj (pid:"+self.proc.pid+") - ", self.bundle);

        process.list = (process.list == undefined) ? [] : process.list;
        process.pids = (process.pids == undefined) ? {} : process.pids;

        self.register(self.bundle, self.proc.pid);

        if (usePidFile) {
            pathObj.mkdir( function(err, path){
                console.debug('path created ('+path+') now saving PID ' +  bundle);
                //logger.info('gina', 'PROC:INFO:1', 'path created ('+path+') now saving PID ' +  bundle, __stack);
                //Save file.
                if (!err) {
                    self.PID = self.proc.pid;
                    self.path = path + pathObj.sep;
                    //Add PID file.
                    setPID(self.bundle, self.PID, self.proc);
                    save(self.bundle, self.PID, self.proc)
                }
            })
        }
    }
472309
def pid(self):
        
        try:

            with open(self.pidfile, 'r') as pidfile:

                try:

                    pid = int(pidfile.read().strip())

                except ValueError:

                    return None

                try:

                    os.kill(pid, 0)

                except OSError as e:

                    if e.errno == errno.EPERM:

                        return pid

                    elif e.errno == errno.ESRCH:

                        return None

                    LOG.exception(
                        "os.kill returned unhandled error "
                        "{0}".format(e.strerror)
                    )
                    sys.exit(exit.PIDFILE_ERROR)

                return pid

        except IOError:

            if not os.path.isfile(self.pidfile):

                return None

            LOG.exception("Failed to read pidfile {0}.".format(self.pidfile))
            sys.exit(exit.PIDFILE_INACCESSIBLE)
486309
def post_worker_init(worker):
    
    quit_command = 'CTRL-BREAK' if sys.platform == 'win32' else 'CONTROL-C'
    sys.stdout.write(
        "Django version {djangover}, Gunicorn version {gunicornver}, "
        "using settings {settings!r}\n"
        "Starting development server at {urls}\n"
        "Quit the server with {quit_command}.\n".format(
            djangover=django.get_version(),
            gunicornver=gunicorn.__version__,
            settings=os.environ.get('DJANGO_SETTINGS_MODULE'),
            urls=', '.join('http://{0}/'.format(b) for b in worker.cfg.bind),
            quit_command=quit_command,
        ),
    )
95172
def run_example(path):
    
    cmd = "{0} {1}".format(sys.executable, path)
    proc = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    res = proc.communicate()
    if proc.returncode:
        print(res[1].decode())
    return proc.returncode
8814
def scheduler(rq, ctx, verbose, burst, queue, interval, pid):
    ""
    scheduler = rq.get_scheduler(interval=interval, queue=queue)
    if pid:
        with open(os.path.expanduser(pid), 'w') as fp:
            fp.write(str(os.getpid()))
    if verbose:
        level = 'DEBUG'
    else:
        level = 'INFO'
    setup_loghandlers(level)
    scheduler.run(burst=burst)
946098
def initialize_worker(self, process_num=None):
        
        for p in self.producers:
            p.initialize_worker(process_num)
        # self.initial_state.process = process_num
        self.random.seed(hash(self.seed) + hash(process_num))
167181
def _run_process(self, start_path, stop_path, process_num=0):
        
        # pre processing
        self.producer.initialize_worker(process_num)
        self.consumer.initialize_worker(process_num)

        # processing
        for path in range(start_path, stop_path):
            self._run_path(path)

        # post processing
        self.consumer.finalize_worker(process_num)
97138
def running(self):
        

        # check if task is active and pid file exists
        return (not self._exited and os.path.isfile(self._pidfile)
                and self._task.active)