protected function scryed($total, $workers = 8, array $args) { $quiet = $this->option('quiet'); $pids = []; for ($i = 0; $i < $workers; $i++) { $pids[$i] = pcntl_fork(); switch ($pids[$i]) { case -1: echo "fork error : {$i} \r\n"; exit; case 0: $limit = floor($total / $workers); $offset = $i * $limit; if ($i == $workers - 1) { $limit = $total - $offset; } $this->info(">>> 一个子进程已开启 | 剩 " . ($workers - $i - 1) . " 个 | pid = " . getmypid() . " | --limit = {$limit} | --offset = {$offset}"); sleep(2); // 这个sleep仅为看清上面的info,可删 array_push($args, "--limit={$limit}", "--offset={$offset}"); $quiet && array_push($args, '--quiet'); pcntl_exec('/usr/bin/php', $args, []); // exec("/usr/bin/php5 artisan crawler:model autohome --sych-model=false --offset={$offset} --limit={$limit}"); // pcntl_exec 与 exec 同样可以执行命令。区别是exec 不会主动输出到shell控制台中 exit; default: break; } } foreach ($pids as $pid) { $pid && pcntl_waitpid($pid, $status); } }
function pleac_Gathering_Output_from_a_Program() { // Run a command and return its results as a string. $output_string = shell_exec('program args'); // Same as above, using backtick operator. $output_string = `program args`; // Run a command and return its results as a list of strings, // one per line. $output_lines = array(); exec('program args', $output_lines); // ----------------------------- // The only way to execute a program without using the shell is to // use pcntl_exec(). However, there is no way to do redirection, so // you can't capture its output. $pid = pcntl_fork(); if ($pid == -1) { die('cannot fork'); } elseif ($pid) { pcntl_waitpid($pid, $status); } else { // Note that pcntl_exec() automatically prepends the program name // to the array of arguments; the program name cannot be spoofed. pcntl_exec($program, array($arg1, $arg2)); } }
function update_main() { global $argc, $argv; global $gbl, $sgbl, $login, $ghtml; debug_for_backend(); $program = $sgbl->__var_program_name; $login = new Client(null, null, 'upgrade'); $opt = parse_opt($argv); print "Getting Version Info from the Server...\n"; if (isset($opt['till-version']) && $opt['till-version'] || lxfile_exists("__path_slave_db")) { $sgbl->slave = true; $upversion = findNextVersion($opt['till-version']); $type = 'slave'; } else { $sgbl->slave = false; $upversion = findNextVersion(); $type = 'master'; } print "Connecting... Please wait....\n"; if ($upversion) { do_upgrade($upversion); print "Upgrade Done.. Executing Cleanup....\n"; flush(); } else { print "{$program} is the latest version\n"; } if (is_running_secondary()) { print "Not running Update Cleanup, because this is running secondary \n"; exit; } lxfile_cp("htmllib/filecore/php.ini", "/usr/local/lxlabs/ext/php/etc/php.ini"); $res = pcntl_exec("/bin/sh", array("../bin/common/updatecleanup.sh", "--type={$type}")); print "Done......\n"; }
function pleac_Replacing_the_Current_Program_with_a_Different_One() { // Transfer control to the shell to run another program. pcntl_exec('/bin/sh', array('-c', 'archive *.data')); // Transfer control directly to another program. pcntl_exec('/path/to/archive', array('accounting.data')); }
/** * Restarts the current server * Only works on Linux (not MacOS and Windows) * * @return void */ function restart() { if (!function_exists("pcntl_exec")) { return; } global $handler; fclose($handler->getServer()->__socket); pcntl_exec($_SERVER["_"], $_SERVER["argv"]); }
function pleac_Running_Another_Program() { // Run a simple command and retrieve its result code. exec("vi {$myfile}", $output, $result_code); // ----------------------------- // Use the shell to perform redirection. exec('cmd1 args | cmd2 | cmd3 >outfile'); exec('cmd args <infile >outfile 2>errfile'); // ----------------------------- // Run a command, handling its result code or signal. $pid = pcntl_fork(); if ($pid == -1) { die('cannot fork'); } elseif ($pid) { pcntl_waitpid($pid, $status); if (pcntl_wifexited($status)) { $status = pcntl_wexitstatus($status); echo "program exited with status {$status}\n"; } elseif (pcntl_wifsignaled($status)) { $signal = pcntl_wtermsig($status); echo "program killed by signal {$signal}\n"; } elseif (pcntl_wifstopped($status)) { $signal = pcntl_wstopsig($status); echo "program stopped by signal {$signal}\n"; } } else { pcntl_exec($program, $args); } // ----------------------------- // Run a command while blocking interrupt signals. $pid = pcntl_fork(); if ($pid == -1) { die('cannot fork'); } elseif ($pid) { // parent catches INT and berates user declare (ticks=1); function handle_sigint($signal) { echo "Tsk tsk, no process interruptus\n"; } pcntl_signal(SIGINT, 'handle_sigint'); while (!pcntl_waitpid($pid, $status, WNOHANG)) { } } else { // child ignores INT and does its thing pcntl_signal(SIGINT, SIG_IGN); pcntl_exec('/bin/sleep', array('10')); } // ----------------------------- // Since there is no direct access to execv() and friends, and // pcntl_exec() won't let us supply an alternate program name // in the argument list, there is no way to run a command with // a different name in the process table. }
function cli_edit($post) { if ($editor = $GLOBALS['EDITOR']) { } else { if ($editor = getenv('EDITOR')) { } else { $editor = "vi"; } } $command = rtrim(`which {$editor}`); if ($command) { pcntl_exec($command, array($post), $_ENV); } }
public function execute() { while (@ob_end_flush()) { } $php = $_SERVER['_']; $host = $this->options->host ?: 'localhost'; $port = $this->options->port ?: '8000'; chdir(PH_APP_ROOT . DIRECTORY_SEPARATOR . 'webroot'); if (extension_loaded('pcntl')) { pcntl_exec($php, array('-S', "{$host}:{$port}", 'index.php')); } else { $this->logger->info("Starting server at http://{$host}:{$port}"); passthru($php . ' ' . join(' ', array('-S', "{$host}:{$port}", 'index.php'))); } }
public function spawn($path, $args = [], $envs = []) { $ret = false; $pid = $this->fork(); if (0 === $pid) { if (false === pcntl_exec($path, $args, $envs)) { exit(0); } } elseif ($pid > 0) { $ret = $pid; } else { // nothing to do ... } return $ret; }
protected function shutDownCallback() { $_ = $_SERVER['_']; return function () use($_) { global $argv; $argvLocal = $argv; array_shift($argvLocal); // @codeCoverageIgnoreStart if (!defined('UNIT_TESTING')) { pcntl_exec($_, $argvLocal); } // @codeCoverageIgnoreEnd return; }; }
/** * {@inheritdoc} */ protected function execute(InputInterface $input, OutputInterface $output) { $userInteraction = new ConsoleUserInteraction($input, $output); $processRunner = new InteractiveProcessRunner($userInteraction); if (!$this->inHomeDirectory()) { $output->writeln('<error>The project have to be in your home directly to be able to share it with the Docker VM</error>'); return 1; } try { $dockerComposePath = $this->getDockerComposePath($processRunner); pcntl_exec($dockerComposePath, ['up']); return 0; } catch (ProcessFailedException $e) { return 1; } }
function launch() { $this->concentrator_pid = pcntl_fork(); if ($this->concentrator_pid == -1) { $errno = posix_get_last_error(); throw new Exception("Error forking off mysql concentrator: {$errno}: " . posix_strerror($errno) . "\n"); } elseif ($this->concentrator_pid == 0) { $cmd = "/usr/bin/php"; $args = array("{$this->bin_path}", "-h", $this->settings['host'], '-p', $this->settings['port']); if (array_key_exists('listen_port', $this->settings)) { $args[] = '-l'; $args[] = $this->settings['listen_port']; } chdir(dirname(__FILE__)); pcntl_exec("/usr/bin/php", $args); throw new Exception("Error executing '{$cmd} " . implode(" ", $args) . "'"); } }
public function coerceWritable($wait = 1) { try { $this->assertWritable(); } catch (UnexpectedValueException $e) { if (!function_exists('pcntl_exec')) { $this->log('<error>' . $e->getMessage() . '</error>'); return; } $this->log('<info>' . $e->getMessage() . ', trying to re-spawn with correct config</info>'); if ($wait) { sleep($wait); } $args = array_merge(array('php', '-d phar.readonly=off'), $_SERVER['argv']); if (pcntl_exec('/usr/bin/env', $args) === false) { $this->log('<error>Unable to switch into new configuration</error>'); return; } } }
/** * Test that the table is actually locked. */ public function test02() { $application = new Application(); $application->add(new AuditCommand()); // Start process that inserts rows into TABLE1. $pid = pcntl_fork(); if ($pid == 0) { // Child process. pcntl_exec(__DIR__ . '/config/generator.php'); } // Parent process. sleep(2); /** @var AuditCommand $command */ $command = $application->find('audit'); $command->setRewriteConfigFile(false); $commandTester = new CommandTester($command); $commandTester->execute(['command' => $command->getName(), 'config file' => __DIR__ . '/config/audit.json']); // Tell the generator it is time to stop. posix_kill($pid, SIGUSR1); $status = $commandTester->getStatusCode(); $this->assertSame(0, $status, 'status code'); pcntl_waitpid($pid, $status); $this->assertEquals(0, $status); // Reconnect to DB. StaticDataLayer::connect('localhost', 'test', 'test', self::$dataSchema); // It can take some time before that all rows generated by $generator are visible by this process. $n1 = 0; $n2 = 0; sleep(5); for ($i = 0; $i < 60; $i++) { $n1 = StaticDataLayer::executeSingleton1("select AUTO_INCREMENT - 1 \n from information_schema.TABLES\n where TABLE_SCHEMA = 'test_data'\n and TABLE_NAME = 'TABLE1'"); $n2 = StaticDataLayer::executeSingleton1('select count(*) from test_audit.TABLE1'); if (4 * $n1 == $n2) { break; } sleep(3); } $this->assertEquals(4 * $n1, $n2, 'count'); }
<?php pcntl_exec("/bin/sh", array(__DIR__ . "/test_pcntl_exec.sh"), array("name" => "value"));
/** * Exec * * @param string $path The path to a binary executable or a script with a valid path pointing to an executable in the shebang * @param array $args Array of argument strings passed to the program. * @param array $envs Array of strings which are passed as environment to the program * * @return null|bool Returns FALSE on error and does not return on success. */ public function exec($path, array $args = array(), array $envs = array()) { return pcntl_exec($path, $args, $envs); }
function update_main() { global $argc, $argv; global $gbl, $sgbl, $login, $ghtml; debug_for_backend(); $prognameNice = $sgbl->__var_program_name_nice; $login = new Client(null, null, 'upgrade'); $opt = parse_opt($argv); print "Getting Version Info from the Server...\n"; print "Connecting... Please wait....\n"; if (isset($opt['till-version']) && $opt['till-version'] || lxfile_exists("__path_slave_db")) { $sgbl->slave = true; $upversion = findNextVersion($opt['till-version']); $type = 'slave'; } else { $sgbl->slave = false; $upversion = findNextVersion(); $type = 'master'; } $thisversion = $sgbl->__ver_major_minor_release; if ($upversion) { do_upgrade($upversion); print "Upgrade Done!\nStarting the Cleanup.\n"; flush(); } else { print "{$prognameNice} is the latest version ({$thisversion})\n"; print "Run 'sh /script/cleanup' if you want restore/fix possible issues.\n"; exit; } if (is_running_secondary()) { print "Not running the Update Cleanup, because this server is a secondary.\n"; exit; } // Needs to be here. So any php.ini change takes immediately effect. print "Copy Core PHP.ini\n"; lxfile_cp("htmllib/filecore/php.ini", "/usr/local/lxlabs/ext/php/etc/php.ini"); pcntl_exec("/bin/sh", array("../bin/common/updatecleanup-core.sh", "--type={$type}")); print "{$prognameNice} is Ready!\n\n"; }
function shellpcntl($cmd) { if (!function_exists('pcntl_exec')) { return false; } $args = explode(' ', $cmd); $path = $args[0]; unset($args[0]); if (pcntl_exec($path, $args) === false) { return false; } else { return 'El comando fue ejecutado, pero no se pudo recuperar la salida'; } }
public function restart() { $serialized = serialize($this); $file = realpath(__DIR__ . "/../../bin/gearman_restart"); $serializedFile = sys_get_temp_dir() . '/gearman_restart_' . uniqid(); file_put_contents($serializedFile, $serialized); if ($file && is_executable($file)) { pcntl_exec($file, ['serialized' => $serializedFile]); exit; } elseif ($file) { $dir = dirname($file); $content = file_get_contents($dir . '/gearman_restart_template'); $content = str_replace('%path', $dir . '/gearman_restart.php', $content); $newFile = sys_get_temp_dir() . '/gearman_restart_' . uniqid(); file_put_contents($newFile, $content); chmod($newFile, 0755); pcntl_exec($newFile, ['serialized' => $serializedFile]); unlink($newFile); exit; } }
global $sock, $db; echo "\n\nctrl-c or kill signal received. Tidying up ... "; socket_shutdown($sock, 0); socket_close($sock); $db = null; die("Bye!\n"); }); pcntl_signal_dispatch(); // let's try and connect echo "Listen to acarsdec ... "; // create our socket and set it to non-blocking $sock = socket_create(AF_INET, SOCK_DGRAM, 0) or die("Unable to create socket\n"); // Bind the source address if (!socket_bind($sock, $globalACARSHost, $globalACARSPort)) { $errorcode = socket_last_error(); $errormsg = socket_strerror($errorcode); die("Could not bind socket : [{$errorcode}] {$errormsg} \n"); } echo "LISTEN UDP MODE \n\n"; while (1) { $r = socket_recvfrom($sock, $buffer, 512, 0, $remote_ip, $remote_port); // lets play nice and handle signals such as ctrl-c/kill properly pcntl_signal_dispatch(); $dataFound = false; // (null) 2 23/02/2015 14:46:06 0 -16 X .D-AIPW ! 1L 7 M82A LH077P 010952342854:VP-MIBI+W+0)-V+(),GB1 $ACARS::add(trim($buffer)); socket_sendto($sock, "OK " . $buffer, 100, 0, $remote_ip, $remote_port); $ACARS::deleteLiveAcarsData(); } pcntl_exec($_, $argv);
/** * Kills the current process and starts a new one */ public function reRunSuite() { $args = $_SERVER['argv']; $env = $this->executionContext ? $this->executionContext->asEnv() : array(); pcntl_exec($this->getExecutablePath(), $args, array_merge($env, $_SERVER)); }
function restart($start = 0) { global $argv; $this->cleanup(); $args = $argv; array_unshift($args, '-d', 'memory_limit=' . ini_get('memory_limit')); foreach ($args as $key => $arg) { if ($arg == '--clear' || $arg == '-c') { $args[$key] = '--force'; } } array_push($args, '--start', $start); pcntl_exec($_SERVER['_'], $args); exit; }
#!/usr/bin/php <?php $args = $argv; $args[0] = '--recv'; pcntl_exec('bin/elastix-faxevent', $args, $_ENV);
$active++; if (count($pid) >= MAX_PROC) { if (DEBUG) { print "[DBG]\t\tMAX_PROC reached!\n"; } while (!file_exists('/tmp/' . str_replace(array(':', '/'), '_', $base) . '.code') && $active > MAX_PROC) { pcntl_wait($status); sleep(SLEEP); } } $active--; } else { if (DEBUG) { echo 'new streamer: ' . PHP_BIN . ' ' . CM_HOME . "/bin/streamer.php {$flux} {$base}\n"; } if (!pcntl_exec(PHP_BIN, array(CM_HOME . '/bin/streamer.php', $flux, $base))) { if (DEBUG) { print "[DBG]\t\tpcnt_exec failed!\n"; } } exit(0); } } if (DEBUG) { print "[DBG]\tend test (" . date("c") . ")\n"; } } /* while (count(glob("/tmp/*.code")) < $todo) sleep(1); exec('killall -9 vlc tee &> /dev/null');
/** * Run the PHP Code in a standalone process and in background * So classes and functions available in your script are NOT available in the new PHP code * and the parent script will not wait the child response * * @param string $code PHP Code * @param array $variables Array of variables to pass at new PHP script * @param boolean $debug If TRUE the parent script wait for the child execution printing his output * @throws \Exception If is not possibile to fork the PHP process */ public function runInBackground($code, $variables = array(), $debug = false) { $_PhpSandboxFullPath = $this->getPhpSandboxDir() . DIRECTORY_SEPARATOR . $this->getUniqueToken($code) . '.php'; $this->mkdir(); $this->phpLastCode = $this->preparePhpCode($code, false, true); file_put_contents($_PhpSandboxFullPath, $this->phpLastCode); $pid = pcntl_fork(); if ($pid == -1) { throw new \Exception('Could not fork'); } else { if ($pid) { if ($debug) { pcntl_waitpid($pid, $status); } } else { pcntl_exec($this->phpBinary, array($_PhpSandboxFullPath), $variables); } } }
/** * Spawn * * @param string $program Program * @param array $arguments Arguments * * @return int */ protected function spawn($program, array $arguments) { // PHP-style spawn... $pid = pcntl_fork(); if ($pid < 0) { $this->fail("Couldn't spawn: {$pid}"); } if ($pid > 0) { return $pid; } pcntl_exec($program, $arguments); // We are in the child, we can finish here. // The program only gets here in case of an error. die; }
/** * Self-update */ function runSelfUpdate() { echo "Performing self-update...\n"; $_tempFileName = INVNAME . ".tmp"; // Download new version echo "Downloading latest version..."; global $UPDATE_BASE; $_fileContents = @file_get_contents($UPDATE_BASE . "/" . SELF); if (strlen($_fileContents) <= 0) { echo "Failed: Error while trying to download new version!\n"; echo "File requested: " . $UPDATE_BASE . "/" . SELF . "\n"; exit(1); } $_payload = split("\n", $_fileContents, 2); echo "Done.\n"; // Restore shebang $_selfContent = split("\n", file_get_contents(INVNAME), 2); $_interpreter = $_selfContent[0]; file_put_contents($_tempFileName, $_interpreter . "\n"); file_put_contents($_tempFileName, $_payload[1], FILE_APPEND); // Copy over modes from old version $_octalMode = fileperms(INVNAME); if (FALSE == chmod($_tempFileName, $_octalMode)) { echo "Failed: Error while trying to set mode on {$_tempFileName}.\n"; exit(1); } // Spawn update script $_name = INVNAME; $_updateScript = <<<EOS #!/bin/bash # Overwrite old file with new if mv "{$_tempFileName}" "{$_name}"; then echo "Done." echo "Update complete." rm -- \$0 else echo "Failed!" fi EOS; file_put_contents("updateScript.sh", $_updateScript); echo "Inserting update process..."; file_put_contents("updateScript.sh", $_updateScript); chmod("updateScript.sh", 0700); if (function_exists("pcntl_exec")) { pcntl_exec("/bin/bash", array("./updateScript.sh")); } else { if (function_exists("passthru")) { die(passthru("./updateScript.sh")); } else { die("Please execute ./updateScript.sh now."); } } }
#!/usr/bin/php <?php $child_pid = pcntl_fork(); if ($child_pid == 0) { pcntl_exec("/bin/ls", array("-la")); } elseif ($child_pid != -1) { pcntl_waitpid($child_pid, $status, 0); } ?>
/** * Executa binario passando 2 arquivos para fazer o diff * * @param strign $sArquivoPrimeiraVersao * @param strign $sArquivoSegundaVersao * @access private * @return void */ private function binario($sArquivoPrimeiraVersao, $sArquivoSegundaVersao) { $aParametrosDiff = array(); $sMascaraBinario = $this->getApplication()->getConfig('mascaraBinarioDiff'); if (empty($sMascaraBinario)) { throw new Exception("Mascara para binario do diff não encontrado, verifique arquivo de configuração"); } $aParametrosMascara = String::tokenize($sMascaraBinario); $sBinario = array_shift($aParametrosMascara); if (empty($sBinario)) { throw new Exception("Arquivo binário para diff não encontrado"); } /** * Percorre os parametros e inclui arquivos para diff */ foreach ($aParametrosMascara as $sParametro) { if ($sParametro == '[arquivo_1]') { $sParametro = $sArquivoPrimeiraVersao; } if ($sParametro == '[arquivo_2]') { $sParametro = $sArquivoSegundaVersao; } $aParametrosDiff[] = $sParametro; } $pid = pcntl_fork(); switch ($pid) { case 0: pcntl_exec($sBinario, $aParametrosDiff); break; default: pcntl_waitpid($pid, $status); break; } }
public function run_db_utility() { require_once __DIR__ . "/../halfmoon.php"; $db_config = Utils::A(Config::instance()->db_config, HALFMOON_ENV); switch ($db_config["adapter"]) { case "mysql": if ($db_config["socket"]) { $bin_args = array("-S", $db_config["socket"]); } else { $bin_args = array("-h", $db_config["hostname"], "-P", $db_config["port"]); } array_push($bin_args, "-D"); array_push($bin_args, $db_config["database"]); array_push($bin_args, "-u"); array_push($bin_args, $db_config["username"]); if ($this->include_password) { array_push($bin_args, "--password="******"password"]); } $bin_path = null; foreach (explode(":", getenv("PATH")) as $dir) { if (file_exists($dir . "/mysql")) { $bin_path = $dir . "/mysql"; break; } } if (!$bin_path) { die("cannot find mysql in \$PATH\n"); } pcntl_exec($bin_path, $bin_args); break; default: die($db_config["adapter"] . " not yet supported\n"); } }