Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: how to start a detached process?

Currently my solution is:

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

and in file.php

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

is there any way I can do this just with exec?

like image 845
Dalius Avatar asked Oct 23 '13 23:10

Dalius


2 Answers

No, detaching can't be done with exec() directly (nor shell_exec() or system(), at least not without changing the command, and using third-party tool which does detach).


If you have the pcntl extension installed, it would be:

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;
    }
}

Call it like this:

$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;
like image 58
hek2mgl Avatar answered Oct 22 '22 20:10

hek2mgl


Provided your current user has sufficient permissions to do so this should be possible with exec and alike:

/*
/ 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();
like image 37
Philzen Avatar answered Oct 22 '22 20:10

Philzen