简体   繁体   中英

PHP execute process in background and get results

I'm looking for an easy way to start a process (through php) in the background (I don't want my php script to wait for the end). Although I would need to also have a handle on the process in other to catch the end of its execution to do some afterwork.

So far I manager to start the process with something like

pclose ( popen ( "\"start /B " . $commands . " > log.txt\"", "r" ) );

But I'm not sure on how to find if the process is terminated (and maybe it's too early in the morning but I can't find much about it using popen and start /B)

I'm using the "start" way because ideally the solution should run on both windows and linux.

Any input would be appreciated. Thanks for the help!

I had to perform a similar task, and although I had a slightly different approach, is quite similar to what you are trying to do, and I went through sockets:

1st step: get the process PID and call socket file

            //windows
            $desc = array(
                0 => array("pipe", "r"), 
                1 => array("pipe", "w"),
            );
            $p = proc_open($command, $desc, $pipes);
            $status = proc_get_status($p);
            $ppid = $status["pid"];
            $output = array_filter(explode(" ", shell_exec("wmic process get parentprocessid,processid | find \"$ppid\"")));
            array_pop($output);
            $pid = end($output);

            //unix
            $pid =  trim(shell_exec(sprintf('%s > %s 2>&1 & echo $!', $command,  $outputFile)))

            //Call the daemon with the socket stuff and pass the pid
            shell_exec("path/to/daemon.php $pid");

2nd step: the daemon file

The daemon.php should open a Socket that checks in intervals if the process with given pid is still running, and if not, send a message and exit the process. I didn´t post the socket stuff because I think there are good libraries for that, and my approach was hand-made what can make it difficult to understand.

3rd: process socket messages where needed

Probably you want to do that in javascript

<script language="javascript" type="text/javascript">  
$(document).ready(function(){
    var wsUri = "ws://host:port/daemon.php";    
    websocket = new WebSocket(wsUri); 

    websocket.onopen = function(ev) { 
    }   
    websocket.onmessage = function(ev) {
        var msg = JSON.parse(ev.data);
        switch( msg.action){
            case "process_finisihed":{
                //doThingsHere
            }
            break;

        }
    };

    websocket.onerror   = function(ev){ console.debug(ev); }; 
    websocket.onclose   = function(ev){}; 
});
</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM