Creating child process using fork

suggest change

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.

Feedback about page:

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


Multiprocessing:
* Creating child process using fork

Table Of Contents
2 Arrays
4 Types
10 Cookies
14 JSON
15 SOAP
17 cURL
19 XML
21 Traits
35 UTF-8
36 URLs
38 PHPDoc
41 Loops
44 Closur
72 YAML
74 Multiprocessing
77 Cache
78 Streams
81 PDO
82 SQLite3
83 Sockets
87 MongoDB
93 IMAP
94 Redis
95 Imagick
102 APCu
108 PSR