Launch sub process

@return array The new sub process and its STDIN, STDOUT, STDERR pipes – or false if an error occurred.
@throws \RuntimeException
164158
protected function launchSubProcess(): array
    {
        $systemCommand = 'FLOW_ROOTPATH=' . FLOW_PATH_ROOT . ' FLOW_PATH_TEMPORARY_BASE=' . FLOW_PATH_TEMPORARY_BASE . ' ' . 'FLOW_CONTEXT=' . $this->bootstrap->getContext() . ' ' . PHP_BINARY . ' -c ' . php_ini_loaded_file() . ' ' . FLOW_PATH_FLOW . 'Scripts/flow.php' . ' --start-slave';
        $descriptorSpecification = [['pipe', 'r'], ['pipe', 'w'], ['pipe', 'a']];
        $subProcess = proc_open($systemCommand, $descriptorSpecification, $pipes);
        if (!is_resource($subProcess)) {
            throw new \RuntimeException('Could not execute sub process.');
        }

        $read = [$pipes[1]];
        $write = null;
        $except = null;
        $readTimeout = 30;

        stream_select($read, $write, $except, $readTimeout);

        $subProcessStatus = proc_get_status($subProcess);
        return ($subProcessStatus['running'] === true) ? [$subProcess, $pipes] : false;
    }
419696
protected function exec()
    {
        $descriptors = [
           0 => ["pipe", "r"],  // stdin is a pipe that the child will read from
           1 => ["pipe", "w"],  // stdout is a pipe that the child will write to
           2 => ["pipe", "w"] // stderr is a file to write to
        ];
        
        $process = proc_open($this->getCommand(), $descriptors, $pipes, dirname($this->getJarPath()), []);

        if (is_resource($process)) {
            fclose($pipes[0]); // close stdin pipe
            $this->output = stream_get_contents($pipes[1]);
            $this->errors = stream_get_contents($pipes[2]);
            fclose($pipes[2]);
            fclose($pipes[1]);                       
            if(proc_close($process) === -1) {
                throw new RuntimeException($this->errors);
            }
        }            
    }
884402
protected function doExecute()
    {
        if ($this->console->getMode() !== 'dev') {
            throw new \RuntimeException(
                '<error>STOP!</error> please run <info>' . $this->getEnvCmd() . '</info>.'
            );
        }

        if (!(new BooleanPrompter())
            ->ask('This action will drop all tables, do you really want to do this? [N/y]', false)) {
            $this->out('  Canceled.');

            return false;
        }

        if (!$this->io->getOption('no-backup')) {
            // backup
            $this->backup();
        }

        $db = $this->console->database;

        $tables = $db->getDatabase()->getTables(true);

        foreach ($tables as $table) {
            $db->getTable($table, true)->drop(true);

            $this->out('  Drop table: <comment>' . $table . '</comment>');
        }

        return true;
    }
390670
public function start()
    {
        $this->logger->info("crontab start");
        $crontab = $this->createCrontab();
        $loop = Factory::create();

        // add periodic timer
        $loop->addPeriodicTimer(60, function () use ($crontab, $loop) {
            $loop->addTimer(60 - time() % 60, function () use ($crontab) {
                $pid = pcntl_fork();
                if ($pid > 0) {
                    return;
                } elseif ($pid == 0) {
                    $crontab->start(time());
                    exit();
                } else {
                    $this->logger->error("could not fork");
                }
            });
        });

        // recover the sub processes
        $loop->addPeriodicTimer(60, function () {
            while (($pid = pcntl_waitpid(0, $status, WNOHANG)) > 0) {
                $message = "process exit. pid:" . $pid . ". exit code:" . $status;
                $this->logger->info($message);
            }
        });

        $loop->run();
    }
646106
public function start()
    {
        if (!$this->process->isStarted()) {
            $this->setStarted();
            $this->dispatch(RunEvent::STARTED, new RunEvent($this));
            $this->process->start(
                function ($type, $data) {
                    $this->lastType = $type;
                    foreach (explode("\n", $data) as $line) {
                        $line = rtrim($line);
                        if (mb_strlen($line) > 0) {
                            $this->last = $line;
                            if ($this->updateOnProcessOutput) {
                                $this->dispatch(RunEvent::UPDATED, new RunEvent($this));
                            }
                        }
                    }
                }
            );
            $this->completed = false;
        }

        return $this;
    }
537838
protected function runInsertSudoerProcess() 
    {
        if (!$this->input->getOption('user_name') || !$this->input->getOption('user_password') || !$this->input->getOption('user_email')) {
            $this->output->writeln('<info>You have to specify all option in order to insert a new superadmin user (--user_name, --user_password, --user_email)</info>');
            return $this;
        }

        # Check if user already exists in db
        if (null === $adminUser = $this->entyMgr
                        ->getRepository('BackBee\Security\User')
                        ->findOneBy(array('_login' => $this->input->getOption('user_name')))) {
            $adminUser = $this->createUser(
                            $this->input->getOption('user_name'),
                            $this->input->getOption('user_password'),
                            $this->input->getOption('user_email')
                        );
            $this->output->writeln('<info>New user created.</info>');
        }

        # Recreate security.yml
        $securityConf = $this->bbapp->getConfig()->getSecurityConfig();
        if (!array_key_exists($adminUser->getLogin(), $securityConf['sudoers'])) {
            $securityConf['sudoers'][$adminUser->getLogin()] = $adminUser->getId();

            file_put_contents(
                $this->bbapp->getBaseDir().DIRECTORY_SEPARATOR.'repository/Config/security.yml',
                Yaml::dump($securityConf)
            );

            $this->output->writeln('<info>User added in security.yml file.</info>');
        }

        return $this;
    }
491253
public function run()
    {
        $port = (int) $this->arg->options('--port', 5000);

        $hostname = $this->arg->options('--host', 'localhost');

        $settings = $this->arg->options('--php-settings', false);

        if (is_bool($settings)) {
            $settings = '';
        } else {
            $settings = '-d '.$settings;
        }

        // resource.
        $writing_stream = fopen("php://stdout", "w");

        $message = sprintf(
            "[%s] Server start at http://%s:%s \033[0;31;7mCTRL-C for shutdown it\033[00m\n",
            date('F d Y H:i:s a'),
            $hostname,
            $port
        );

        fwrite($writing_stream, $message);

        // Close Open stream
        fclose($writing_stream);

        $filename = $this->setting->getServerFilename();
        $public_directory = $this->setting->getPublicDirectory();

        // Launch the dev server.
        shell_exec(
            "php -S $hostname:$port -t {$public_directory} ".$filename." $settings"
        );
    }
224135
protected function run()
	{
		fputs( STDOUT, ":> " );
		while( $line = $this->readLine() )
		{
			$line = preg_replace( "/\n*|\r*/", "", $line );
			$line = preg_replace( "/;$/", "", $line );
			if( strlen( $line ) )
			{
				if( $this->isImmediate( $line ) )
					$line = "return( ".$line." )";
				ob_start();
				$ret = eval( "unset(\$line); $line;" );
				if( ob_get_length() == 0)
				{
					if( is_bool( $ret ) )
						echo( $ret ? "true" : "false" );
					else if( is_string( $ret ) )
						echo "'" . addcslashes( $ret, "\0..\37\177..\377" )  . "'";
					else if( !is_null( $ret ) )
						print_r( $ret );
				}
				unset($ret);
				$out = ob_get_contents();
				ob_end_clean();
				if( ( strlen( $out ) > 0) && ( substr( $out, -1 ) != "\n" ) )
					$out .= "\n";
				fputs( STDOUT, "=> ".$out );
				unset( $out );
				fputs( STDOUT, ":> " );
			}
		}
	}
874990
public function run()
    {
 
        
        $sample = file_get_contents($this->parameters['tpl']);
        $target = $this->parameters['target'];
        
        $serverName = $this->parameters['serverName'];
        $documentRoot = $this->parameters['documentRoot'];
        $directory = array();
        
        $it = new RecursiveDirectoryIterator($documentRoot);

        foreach (new RecursiveIteratorIterator($it) as $file) {
            if($file->getFileName() == '.htaccess' 
                && strpos($file->getPath(), 'install/checks/testRewrite') ===false){
              
          
               $pathName = $file->getPathname();
               $path = $file->getPath();
               
               $directory[$path] = "\t<Directory ". $path . ">\n";
               $htaccess = file_get_contents($pathName);
               $directory[$path] .= $htaccess;
               $directory[$path] .= "\n\t</Directory>\n";
               
            }
        }
        
        $directoryContent = implode("\n",array_values($directory));
    
        $maps = array(
        	'{ServerName}' => $serverName,
            '{DocumentRoot}' => $documentRoot,
            '{Directory}' => $directoryContent
        );
        
        $finalContent = str_replace(array_keys($maps), array_values($maps), $sample);
        file_put_contents($target, $finalContent);
    }
850556
public function wait()
    {
        if ($this->process == null) {
            throw new \Exception('You must run `start` before running `wait`');
        }

        // blocks here until process completes
        $this->process->wait();

        if (!$this->process->isSuccessful()) {
            throw new \RuntimeException($this->process->getErrorOutput());
        }

        return $this->process->getOutput();
    }
537875
public function launch()
    {
        try {
            $this->processPipeline();

            $this->response = $this->dispatch($this->request, $this->response);

            if ($this->response instanceof CompiledResponse) {
                $this->response->compileContent();
            }

            return $this->emitter->emit($this->response);
        } catch (\Exception $exception) {
            foreach ($this->exceptions as $exceptionClassName => $callable) {
                if ($exception instanceof $exceptionClassName) {
                    return $callable($this, $exception);
                }
            }

            throw $exception;
        }
    }
613356
public function run()
    {
        $error = $this->error;
        $output = $this->output;

        return $this->builder->getProcess()->run(
            function ($type, $buffer) use ($error, $output) {
                if ('err' === $type) {
                    if ($error) {
                        $error($buffer);
                    }
                } elseif ($output) {
                    $output($buffer);
                }
            }
        );
    }
1210997
public function start()
    {
        $this->events->dispatch(new Events\ServerLaunching($this));

        $this->running = true;

        $this->dispatchEvent('Launching', $this);

        $result = $this->swooleServer->start();

        $this->running = false;

        return $result;
    }
686517
protected function launchNextTask()
    {
        if (! $this->numberOfThreadsToLaunch) {
            return false;
        }
        
        $taskInfos = $this->pool[$this->numberOfTasks - $this->numberOfThreadsToLaunch];
        
        $taskInfos['task']->fork();
        $this->numberOfRunningThreads++;
        $this->numberOfThreadsToLaunch--;
        
        return true;
    }
1033829
public function getCommand()
    {
        $command = $this->getCommandName();

        if (is_null($command)) {
            throw new \RuntimeException("commandName must be specified to build a subcommand");
        }

        $command .= ' ';
        $args = $this->getCommandArguments();
        if (count($args) > 0) {
            $command .= $this->extractArguments($args);
            $command .= ' ';
        }
        $subjects = $this->getCommandSubjects();
        if (count($subjects) > 0) {
            $command .= implode(' ', array_map('escapeshellarg', $subjects));
        }
        $command = preg_replace('/\\s{2,}/', ' ', $command);

        return trim($command);
    }
1363397
public function execute()
    {
        $this->prepareExecute();

        // Show help or not if command has no logic
        if (!count($this->children) && $this->console instanceof AbstractConsole && $this->console->get('show_help')) {
            $this->io->out($this->console->describeCommand($this));

            return $this->postExecute(true);
        }

        if (count($this->children) && count($this->io->getArguments())) {
            $name = $this->io->getArgument(0);

            // Show help if a command also has logic
            if ($this->console instanceof AbstractConsole && $this->console->get('show_help')
                && !isset($this->children[$name])) {
                $this->io->out($this->console->describeCommand($this));

                return $this->postExecute(true);
            }

            try {
                return $this->executeSubCommand($name);
            } catch (CommandNotFoundException $e) {
                $e->getCommand()->renderAlternatives($e->getChild(), $e);

                return $e->getCode();
            } catch (WrongArgumentException $e) {
                $command = $this->getChild($name);

                throw new \RuntimeException(
                    $e->getMessage() . "\n\n[Usage] " . $command->getUsage(),
                    $e->getCode(),
                    $e
                );
            } catch (\Exception $e) {
                throw $e;
            }
        }

        if ($this->handler) {
            if ($this->handler instanceof \Closure) {
                $code = $this->handler;

                return $code($this);
            } elseif (is_callable($this->handler)) {
                return call_user_func($this->handler, $this);
            }
        }

        $result = $this->doExecute();

        return $this->postExecute($result);
    }
514842
public function execute()
	{
		if (count($this->children) && count($this->input->args))
		{
			$name = $this->input->args[0];

			try
			{
				return $this->executeSubCommand($name);
			}
			catch (CommandNotFoundException $e)
			{
				$e->getCommand()->renderAlternatives($e->getChild(), $e);

				return $e->getCode();
			}
			catch (\Exception $e)
			{
				$this->renderException($e);

				return $e->getCode();
			}
		}

		if ($this->handler)
		{
			if ($this->handler instanceof \Closure)
			{
				$code = $this->handler;

				return $code($this);
			}
			elseif (is_callable($this->handler))
			{
				return call_user_func($this->handler, $this);
			}
		}

		return $this->doExecute();
	}