As I’ve written in part 1, the introduction of this series on PHP fork, in this part we will talk about the way processes work in UNIX and Linux, and how we can use this for PHP.
Many information in this article is based on the IBM Developerworks article on UNIX Processes. I added this part for your convenience and for completeness, but I won’t go into detail about UNIX processes. If you want to know more, read the beforementioned article.
Any program in UNIX is a process, except for the kernel. A program is in fact a bunch of data, with some instructions to do something with that data. A process tells when and how these instructions should be executed.
Each process has its own and unique (at that point in time) process id. It is impossible for two processes to have the same process id at the same time. It is, however, possible that some process id is assigned to another process. This only happens when the counter for process id’s runs out of space, and is reset, so that it starts with process id 2 (for process id 1 one never ever stops as long as the system is running).
So, when you launch a new process, that process will get its own, unique process id, which is an identifier in the whole system. Furthermore is the process id used to identify all resources in use by that process. A resource can be defined as anything which is needed to run, such as memory, disk space, a network socket, open files such as logfiles or input/output files and anything als you can think of.
This also means that each PHP program or script you are running, has its own process id, with the possible exception of the PHP scripts running inside a webserver process, like Apache httpd sometimes does.
When you spawn a new process, it internally uses the fork(1) system call, which returns the process id of the child in the parent, 0 in the child or -1 when something bad happened. Using this knowledge, we can check wether we are in the parent or in the child process, and act approriately. More on that in the next part of this tutorial, where we will create a PHP daemon, which will start processes for the sole purpose of saying Hello World multiple times.