Search code examples
phpprocesspopenpidpclose

Executing and get pid a background process in PHP on Windows


I started a process in background in Windows apache server.

index.php following this:

<?php
$cmd = "C:/xampp/php/php.exe -f test.php";
pclose(popen("start /B ". $cmd, "r"));
echo "OK";
?>

test.php following this:

<?php
sleep(5);
file_put_contents("1.txt", date("Y-m-d H:i:s"));
?>

At that time, I want to get pid which php -f test.php. When I start index.php, I can see new php.exe process in output of tasklist command line. How can I get pid for this background process.

Thanks.


Solution

  • This will output the ProcessID after the task has been executed using wmic. You could then store this in a session or cookie to pass between pages.

    $cmd = 'wmic process call create "C:/xampp/php/php.exe -f /path/to/htdocs/test.php" | find "ProcessId"';
    
    $handle = popen("start /B ". $cmd, "r");
    
    $read = fread($handle, 200); //Read the output 
    
    echo $read; //Store the info 
    
    pclose($handle); //Close
    

    Output

    ProcessId = 1000