4

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.

Wen NanZhe
  • 43
  • 6
  • `$pid = getmypid();` http://php.net/manual/en/function.getmypid.php Heed the warning though: **Warning Process IDs are not unique, thus they are a weak entropy source. We recommend against relying on pids in security-dependent contexts.** – icecub Nov 21 '16 at 09:42
  • Thanks for your help. but it returns pid of httpd.exe. I want to get pid of php.exe. – Wen NanZhe Nov 21 '16 at 09:51
  • I don't know what exactly you're doing but keep in mind that this is a CLI command. Meaning this won't work if you run it in a browser. – icecub Nov 21 '16 at 09:57
  • Add this to the top of your code: `if ( PHP_SAPI !== 'cli' ) { die( "Cmd line access only!\n" ); }` to make sure you're not trying to run this anywhere you're not supposed to. – icecub Nov 21 '16 at 10:00
  • I added `$pid = getmypid();` in `index.php`. Because I want to get process status in anytime. If `$pid = getmypid();` insert to `test.php`, it will work fine, but I will get `$pid` after end of process. – Wen NanZhe Nov 21 '16 at 10:02
  • Have a look at this question: http://stackoverflow.com/questions/17874238/php-process-id-and-unique It'll most likely help you out. – icecub Nov 21 '16 at 10:05

1 Answers1

2

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
Kitson88
  • 2,889
  • 5
  • 22
  • 37
  • This doesn't work for me, what did is this https://www.c-sharpcorner.com/code/30/how-to-invokestart-a-process-in-php-and-kill-it-using-process-id.aspx – Calin Dec 05 '18 at 12:06