Backend Development 3 min read

Understanding PHP's pcntl_fork(): Process Creation and Fork Behavior

This article explains PHP's pcntl_fork() function, how it creates child processes on Linux, the return values in parent and child, code examples demonstrating variable copying and process multiplication, and clarifies why a loop with three forks results in seven child processes.

php中文网 Courses
php中文网 Courses
php中文网 Courses
Understanding PHP's pcntl_fork(): Process Creation and Fork Behavior

The pcntl_fork() function, provided by the PHP pcntl extension, is used to create a new process (a child) from the current script; it is not supported on Windows.

The article does not cover how to install or enable the pcntl extension, focusing instead on the behavior of pcntl_fork() itself.

Example code illustrating basic usage:

<code>$one = 123;
$one++;
$two = time();
$pid = [];
$pid = pcntl_fork();
$three = time();</code>

When pcntl_fork() is called, the operating system creates a child process that is an exact copy of the parent, including all data, code, and execution state.

1. After a successful fork, the parent receives the child’s PID, while the child receives 0; on failure, -1 is returned. 2. The child process copies the parent’s code and data, so both have identical variables and logic. 3. Key point: The child starts execution right after the fork call, meaning any code following the fork runs in both processes, and variables such as $one and $two exist in the child as well.

Another example shows a loop that forks multiple times:

<code>for ($i = 0; $i < 3; $i++) {
    $pid = pcntl_fork();
}
sleep(30);</code>

This loop creates a total of seven child processes (plus the original parent, making eight processes visible with ps on Linux). The reason is that each newly created child continues the loop and may create its own children, leading to exponential growth.

In summary, pcntl_fork() duplicates the entire execution environment, and careful control of loops and fork points is essential to avoid unintentionally spawning many processes.

BackendlinuxPHPProcessforkpcntl_fork
php中文网 Courses
Written by

php中文网 Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.