PHP: как запустить отдельный процесс?
В настоящее время мое решение таково:
exec('php file.php >/dev/null 2>&1 &');
И в file.php
if (posix_getpid() != posix_getsid(getmypid()))
posix_setsid();
Могу ли я как-нибудь сделать это просто с помощью exec?
8
2 answers
Нет, это невозможно сделать с помощью exec()
(или shell_exec()
или system()
)
Если у вас установлено расширение pcntl, это будет:
function detached_exec($cmd) {
$pid = pcntl_fork();
switch($pid) {
// fork errror
case -1 : return false
// this code runs in child process
case 0 :
// obtain a new process group
posix_setsid();
// exec the command
exec($cmd);
break;
// return the child pid in father
default:
return $pid;
}
}
Назовем это так:
$pid = detached_exec($cmd);
if($pid === FALSE) {
echo 'exec failed';
}
// do some work
// kill child
posix_kill($pid, SIGINT);
waitpid($pid, $status);
echo 'Child exited with ' . $status;
6
Author: hek2mgl, 2015-07-20 20:57:21
При условии, что ваш текущий пользователь имеет достаточные разрешения для этого, это должно быть возможно с помощью exec
и аналогично:
/*
/ Start your child (otherscript.php)
*/
function startMyScript() {
exec('nohup php otherscript.php > nohup.out & > /dev/null');
}
/*
/ Kill the script (otherscript.php)
/ NB: only kills one process at the time, otherwise simply expand to
/ loop over all complete exec() output rows
*/
function stopMyScript() {
exec('ps a | grep otherscript.php | grep -v grep', $otherProcessInfo);
$otherProcessInfo = array_filter(explode(' ', $otherProcessInfo[0]));
$otherProcessId = $otherProcessInfo[0];
exec("kill $otherProcessId");
}
// ensure child is killed when parent php script / process exits
register_shutdown_function('stopMyScript');
startMyScript();
6
Author: Philzen, 2013-10-24 00:38:26