php-pcntlHow to use the PCNTL_FORK function in PHP?
The PCNTL_FORK function in PHP is used to create a child process from the parent process. It is used to execute multiple tasks simultaneously.
Example code
<?php
$pid = pcntl_fork();
if ($pid == -1) {
     die('could not fork');
} else if ($pid) {
     // we are the parent
     pcntl_wait($status); //Protect against Zombie children
} else {
     // we are the child
     echo "I'm the child\n";
}
?>
Output example
I'm the child
Code explanation
- 
$pid = pcntl_fork();- This line creates a child process from the parent process and stores the process id of the child process in the$pidvariable. - 
if ($pid == -1) {- This line checks if the child process was created successfully. If the value of$pidis-1, it means that the child process was not created successfully. - 
else if ($pid) {- This line checks if the value of$pidis not-1. If it is not-1, it means that the child process was created successfully. - 
pcntl_wait($status);- This line is used to protect against Zombie children. It waits for the child process to finish execution before continuing with the parent process. 
Helpful links
More of Php Pcntl
- How to use PCNTL alarm in PHP?
 - How to use pcntl_wifexited in PHP?
 - How to get the process ID with PHP PCNTL?
 - How to use pcntl_waitpid in PHP?
 - How to use pcntl_fork in PHP?
 - How to use pcntl_wexitstatus in PHP?
 - How to use pcntl_wait in PHP?
 - How to prevent zombie processes with the PCNTL_FORK function in PHP?
 - How to use shared memory with the PCNTL_FORK function in PHP?
 - How to use shared variables with the PCNTL_FORK function in PHP?
 
See more codes...