Creating child process using fork

suggest change

The pcntl extension, which is not available on Windows, provides pcntl_fork() for creating a child process. It matches fork() on Unix: it takes no parameters and returns an integer that distinguishes the parent from the child. Consider the following code:

<?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 is a zombie (defunct) process if the parent exits before the child, or if it never collects the child’s exit status. To collect that status, call pcntl_wait($status) in the parent.

pcntl_wait suspends the parent until a child process has exited.

It is also worth noting that zombie process can’t be killed using SIGKILL signal.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents