PHP has built in function pcntl_fork
for creating child process. pcntl_fork
is same as fork
in unix. It does not take in any parameters and returns integer which can be used to differentiate between parent and child process. Consider the following code for explanation
<?php
// $pid is the PID of child
$pid = pcntl_fork();
if ($pid == -1) {
die('Error while creating child process');
} else if ($pid) {
// Parent process
} else {
// Child process
}
?>
As you can see -1
is an error in fork and the child was not created. On creation of child, we have two processes running with separate PID
.
Another consideration here is a zombie process
or defunct process
when parent process finishes before child process. To prevent a zombie children process simply add pcntl_wait($status)
at the end of parent process.
pnctl_wait suspends execution of parent process until the child process has exited.
It is also worth noting that zombie process
can't be killed using SIGKILL
signal.