Forks into a master and a loop process.

The loop process will handle the evaluation of all instructions, then
return its state via a socket upon completion.

@param Shell $shell
326950
public function beforeRun(Shell $shell)
    {
        list($up, $down) = \stream_socket_pair(STREAM_PF_UNIX, STREAM_SOCK_STREAM, STREAM_IPPROTO_IP);

        if (!$up) {
            throw new \RuntimeException('Unable to create socket pair');
        }

        $pid = \pcntl_fork();
        if ($pid < 0) {
            throw new \RuntimeException('Unable to start execution loop');
        } elseif ($pid > 0) {
            // This is the main thread. We'll just wait for a while.

            // We won't be needing this one.
            \fclose($up);

            // Wait for a return value from the loop process.
            $read   = [$down];
            $write  = null;
            $except = null;

            do {
                $n = @\stream_select($read, $write, $except, null);

                if ($n === 0) {
                    throw new \RuntimeException('Process timed out waiting for execution loop');
                }

                if ($n === false) {
                    $err = \error_get_last();
                    if (!isset($err['message']) || \stripos($err['message'], 'interrupted system call') === false) {
                        $msg = $err['message'] ?
                            \sprintf('Error waiting for execution loop: %s', $err['message']) :
                            'Error waiting for execution loop';
                        throw new \RuntimeException($msg);
                    }
                }
            } while ($n < 1);

            $content = \stream_get_contents($down);
            \fclose($down);

            if ($content) {
                $shell->setScopeVariables(@\unserialize($content));
            }

            throw new BreakException('Exiting main thread');
        }

        // This is the child process. It's going to do all the work.
        if (\function_exists('setproctitle')) {
            setproctitle('psysh (loop)');
        }

        // We won't be needing this one.
        \fclose($down);

        // Save this; we'll need to close it in `afterRun`
        $this->up = $up;
    }
426135
private function exec($interactive = false, $blocking = self::NON_BLOCKING)
    {
        $this->validate();

        $this->resource = proc_open($this->command->serialize(),
                                    $this->descriptorspec,
                                    $this->pipes,
                                    $this->cwd,
                                    null);

        if ($this->resource === false) {
            throw new ProcessException('Call to [proc_open] failed.', $this);
        }

        $this->start = microtime(true);

        $this->running = true;

        if (!$interactive && isset($this->pipes[static::STDIN]) && is_resource($this->pipes[static::STDIN])) {
            fclose($this->pipes[static::STDIN]);
        }

        $this->setStreamBlocking($blocking);
    }
839185
public function fork()
    {
        $pair = $this->pair();

        $pid = pcntl_fork();
        if ($pid < 0) {  // Failed fork
            throw new \RuntimeException('Failed to fork child process.');
        } elseif ($pid === 0) {  // is worker process
            fclose($pair[0]);
            foreach ($this->sockets as $socket) {
                fclose($socket);
            }
            $this->sockets = array();
            $this->loop($pair[1]);
            exit;
        }

        fclose($pair[1]);
        $this->sockets[$pid] = $pair[0];

        return $pid;
    }
840216
private function fork(&$socket) {
        $pair = [];
        if (socket_create_pair(AF_UNIX, SOCK_STREAM, 0, $pair) === false) {
            $this->logger->error('{type}: Unable to create socket pair; ' . socket_strerror(socket_last_error($pair[0])), $this->logContext);

            exit(0);
        }

        $PID = Qless::fork();
        if ($PID !== 0) {
            // MASTER
            $this->childProcesses++;

            $socket = $pair[0];
            socket_close($pair[1]);
            socket_set_option($socket, SOL_SOCKET, SO_RCVTIMEO, ['sec' => 0, 'usec' => 10000]); // wait up to 10ms to receive data

            return $PID;
        }

        $socket = $pair[1];
        socket_close($pair[0]);

        $reserved = str_repeat('x', 20240);

        register_shutdown_function(function () use (&$reserved, $socket) {
            // shutting down
            if (null === $error = error_get_last()) {
                return;
            }
            unset($reserved);

            $type = $error['type'];
            if (!isset(self::$ERROR_CODES[$type])) {
                return;
            }

            $this->logger->debug('Sending error to master', $this->logContext);
            $data = serialize($error);

            while (($len = socket_write($socket, $data)) > 0) {
                $data = substr($data, $len);
            }
        });

        return $PID;
    }
1209424
@Override
  public void process(Node externs, Node root) {
    checkState(topLevelStatements.isEmpty(), "process() called more than once");
    NodeTraversal t = new NodeTraversal(compiler, this, scopeCreator);
    t.traverseRoots(externs, root);
  }
515193
def _detach_process(self):
        """"""
        # First fork to return control to the shell
        pid = os.fork()
        if pid > 0:
            # Wait for the first child, because it's going to wait and
            # check to make sure the second child is actually running
            # before exiting
            os.waitpid(pid, 0)
            sys.exit(0)

        # Become a process group and session group leader
        os.setsid()

        # Fork again so the session group leader can exit and to ensure
        # we can never regain a controlling terminal
        pid = os.fork()
        if pid > 0:
            time.sleep(1)
            # After waiting one second, check to make sure the second
            # child hasn't become a zombie already
            status = os.waitpid(pid, os.WNOHANG)
            if status[0] == pid:
                # The child is already gone for some reason
                exitcode = status[1] % 255
                self._emit_failed()
                self._emit_error('Child exited immediately with exit '
                                 'code {code}'.format(code=exitcode))
                sys.exit(exitcode)
            else:
                self._emit_ok()
                sys.exit(0)

        self._reset_file_descriptors()
65464
public function process(MasterSupervisor $master, array $options)
    {
        $options = SupervisorOptions::fromArray($options);

        $master->supervisors[] = new SupervisorProcess(
            $options, $this->createProcess($master, $options), function ($type, $line) use ($master) {
                $master->output($type, $line);
            }
        );
    }
339116
public function process(Batch $batch)
    {
        $flags = $batch->getFlags();

        foreach ($this->inputs($batch->getInputs()) as $input) {
            foreach ($this->templates($batch->getTemplates()) as $template) {
                $instruction = $this->instructionCreator->createInstruction($input, $template, $flags);

                if (!$instruction) {
                    continue;
                }

                yield $instruction;
            }
        }
    }
634110
def run
      return if pid
      listener_socket, master_socket = UNIXSocket.pair
      if @pid = fork
        # master
        listener_socket.close
        master_socket.close_on_exec = true
        log "Started listener #{@pid}"
        @master_socket = master_socket
      else
        # listener
        master_socket.close
        Master::TRAPS.each { |signal| trap(signal, 'DEFAULT') rescue nil }
        Listener.new(@options.merge(:socket => listener_socket)).exec
        exit
      end
    end
837657
protected function fork_me($method) {
        $this->wait_for_signal = true;
        $pid = pcntl_fork();
        switch ($pid) {
            case 0:
                $this->isparent = false;
                $this->parent_pid = $this->pid;
                $this->pid = getmypid();
                $this->$method();
                break;
            case -1:
                $this->log("Failed to fork");
                $this->stop_work = true;
                break;
            default:
                $this->log("Helper forked with pid $pid", GearmanManager::LOG_LEVEL_PROC_INFO);
                $this->helper_pid = $pid;
                while ($this->wait_for_signal && !$this->stop_work) {
                    usleep(5000);
                    pcntl_waitpid($pid, $status, WNOHANG);

                    if (pcntl_wifexited($status) && $status) {
                         $this->log("Helper child exited with non-zero exit code $status.");
                         exit(1);
                    }

                }
                break;
        }
    }
603840
def do_shell(self, args):
        """'"""
        if _debug: ConsoleCmd._debug("do_shell %r", args)

        os.system(args)
355961
def process_shell(self, creator, entry, config):
        """"""
        self.logger.info("Processing Bash code: start")

        output = []
        shell = creator(entry, config)
        for line in shell.process():
            output.append(line)
            self.logger.info(" | %s", line)

        if shell.success:
            self.logger.info("Processing Bash code: finished")
            return {'success': True, 'output': output}

        for line in self.run_cleanup(config.env, shell.exit_code):
            output.append(line)

        self.logger.error("Pipeline has failed: leaving as soon as possible!")
        self.event.failed()
        return {'success': False, 'output': output}
416675
public function exec()
    {
        $process = Seeds::exec();
        //
        $this->show($process);
        $this->backup($process);
    }
72309
public function out($msg)
    {
        if (!empty($this->controller->Flash)) {
            $this->controller->Flash->success($msg);
        } else {
            $this->Shell->out($msg);
        }
    }
907139
protected function loop($socket)
    {
        while (true) {
            try {
                $result = $this->read($socket);  // is blocking
            } catch (\RuntimeException $e) {
                break;
            }
            $this->write($socket, call_user_func($this->procedure, $result));
        }
    }
377687
def do_shell(self, arg):
        
        if self.cmdprefix:
            raise CmdError("prefix not allowed")

        # Try to use the environment to locate cmd.exe.
        # If not found, it's usually OK to just use the filename,
        # since cmd.exe is one of those "magic" programs that
        # can be automatically found by CreateProcess.
        shell = os.getenv('ComSpec', 'cmd.exe')

        # When given a command, run it and return.
        # When no command is given, spawn a shell.
        if arg:
            arg = '%s /c %s' % (shell, arg)
        else:
            arg = shell
        process = self.debug.system.start_process(arg, bConsole = True)
        process.wait()
1171962
def execute(cls, command, shell=True):
        
        cls.debug('execute command (shell flag:%r): %r ' % (shell, command))
        try:
            check_call(command, shell=shell)
            return True
        except CalledProcessError:
            return False