php execute a background process

前端 未结 19 1441
萌比男神i
萌比男神i 2020-11-21 07:04

I need to execute a directory copy upon a user action, but the directories are quite large, so I would like to be able to perform such an action without the user being aware

19条回答
  •  不思量自难忘°
    2020-11-21 07:39

    Assuming this is running on a Linux machine, I've always handled it like this:

    exec(sprintf("%s > %s 2>&1 & echo $! >> %s", $cmd, $outputfile, $pidfile));
    

    This launches the command $cmd, redirects the command output to $outputfile, and writes the process id to $pidfile.

    That lets you easily monitor what the process is doing and if it's still running.

    function isRunning($pid){
        try{
            $result = shell_exec(sprintf("ps %d", $pid));
            if( count(preg_split("/\n/", $result)) > 2){
                return true;
            }
        }catch(Exception $e){}
    
        return false;
    }
    

提交回复
热议问题