Get a PHP Script’s Own Linux PID (Process Id)
By marc • May 14th, 2008 • Category: PHPPreviously, I wrote this article on how to check the status of a known system PID from PHP. I figured that I would follow it up with another short article on how to determine the process id of a running PHP script from within itself. Many google searches seem to have led people to the previous article, so I want to round everything out for those that need to get the PID in the first place.
So, why would you want to know the PID of a running PHP script anyways?
Occasionally I have written some specific jobs that are to run in an infinite loop to handle data processing on a server. Since these types of scripts get fired up once in the background, I need to be able to check the status from another PHP application that is managing the state of several of these looping processes.
Basically I need to get the PHP script’s PID from itself and then store that somewhere (database, memcache, text file, etc) so that the other application can check the status, etc.
So in order to achieve this, all we have to do is this:
-
-
// get my pid!
-
$pid = getmypid();
-
-
// do something with it (i.e. store somewhere for later retrieval)….
Wow, that was simple! Check out my previous article to see how you can check on the PID from another script once you know what it is.
The book Advanced PHP Programming by George ​Schlossnagle describes this well.