Invoke external shell script from PHP and get its process ID

隐身守侯 提交于 2019-11-27 02:06:43

问题


How can I invoke an external shell script (Or alternatively an external PHP script) from PHP itself and get its process ID within the same script?


回答1:


$command =  'yourcommand' . ' > /dev/null 2>&1 & echo $!; ';

$pid = exec($command, $output);

var_dump($pid);



回答2:


If you want to do this strictly using tools PHP gives you, rather than Unix-specific wizardry, you can do so with proc_open and proc_get_status, although the need to pass a descriptor spec into proc_open makes it unpleasantly verbose to use:

<?php

$descriptorspec = [
    0 => ['pipe', 'r'],
    1 => ['pipe', 'w'],
    2 => ['pipe', 'w']
];
$proc = proc_open('yourcommand', $descriptorspec, $pipes);
$proc_details = proc_get_status($proc);
$pid = $proc_details['pid'];

echo $pid;



回答3:


For a cross-platform solution, check out symfony/process.

use Symfony\Component\Process\Process;
$process = new Process('sleep 100');
$process->start();
var_dump($process->getPid());

After you install symfony/process with composer (composer require symfony/process), you may need to update autoloading info with composer dump-autoload and then require the autoload with require __DIR__ . '/vendor/autoload.php';.

Notice also that you can get PID of a running process only. Refer to the documentation for API details.



来源:https://stackoverflow.com/questions/1470910/invoke-external-shell-script-from-php-and-get-its-process-id

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!