arrow_back
Back

PCNTL in PHP: process forking and parallel work

Andrew Dorokhov Andrew Dorokhov schedule 2 min read
menu_book Table of Contents

Useful reading:

Overview

For process control in PHP there is the pcntl extension. It does not create threads; it forks processes.

if (!function_exists('pcntl_fork')) {
    throw new Exception('No pcntl');
}

$pid = pcntl_fork();

if (-1 === $pid) {
    throw new Exception('pcntl error');
}

if (0 !== $pid) {
    return $pid;
}

register_shutdown_function(function () {
    ob_end_clean();
    posix_kill(getmypid(), SIGKILL);
});

// Child process work goes here

exit(0);

In this example the child is killed with posix_kill because the parent may already have finished. If you do not clean up children properly, you can end up with zombies and leftover resources (files, DB connections).

Fork

A fork creates a copy of the current process. After forking you often need new descriptors to talk to external resources, because sharing the parent’s open connections is unsafe.

Important: processes are not threads

Child processes are isolated from the parent:

  • They do not share memory the way threads do.
  • Changing a variable in the parent does not change the copy in the child (and vice versa).
  • They cannot casually share state; you need IPC if they must communicate.

Side note. If you kill the parent and leave a child in an infinite loop, control may return to the shell — roughly similar in spirit to backgrounding with &.

code

Need Help with Development?

Happy to help — reach out via the contacts or go straight to my Upwork profile.

work View Upwork Profile arrow_forward
Next Article

pthreads in PHP: threads, workers, and synchronization

arrow_forward