profile picture

PHP daemon with fork howto part 2: About UNIX processes and PHP

Published on 17 October 2008 - php php-fork-series work

This content is old and may be outdated.

As promised in part 1, the introduction of this series on PHP fork, now we will talk about the way processes work in UNIX and Linux, and how we can use these from PHP.

Much of the 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 aforementioned 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 a new process is launched, that process will get its own, unique process id, which is an identifier in the whole system. Furthermore, the process id is 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 else 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.

Spawning a new process is done by calling the fork(1) system call, which returns one of three values:

Using this knowledge, we can check whether we are in the parent or in the child process, and act appropriately.

More on that in the next part of this series. There we will create a PHP daemon, which will start processes for the sole purpose of saying Hello World multiple times.