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 に答える