PHP: how to start a detached process?

后端 未结 2 1173
隐瞒了意图╮
隐瞒了意图╮ 2021-01-12 05:20

Currently my solution is:

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

and in file.php

if (posix_getpid() != pos         


        
2条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-12 05:40

    No this can't be done with exec() (nor shell_exec() or system())


    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
    
    // kill child
    posix_kill($pid, SIGINT);
    waitpid($pid, $status);
    
    echo 'Child exited with ' . $status;
    

提交回复
热议问题