9

目前我的解决方案是:

exec('php file.php >/dev/null 2>&1 &');

并在 file.php

if (posix_getpid() != posix_getsid(getmypid()))
    posix_setsid();

有什么办法可以只用 exec 做到这一点?

4

2 回答 2

18

,不能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 ...

// Optionally, kill child process (if no longer required).
posix_kill($pid, SIGINT);
waitpid($pid, $status);

echo 'Child exited with ' . $status;
于 2013-10-23T23:09:28.840 回答
7

如果您当前的用户有足够的权限这样做,那么这应该是可能的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();
于 2013-10-23T23:44:56.460 回答