Parallel processing in PHP using pcntl_fork() Explanation

By XiaoXin
A Bit Randomly

$fp = fopen("/tmp/lock.txt","w+"); if (flock($fp , LOCK_EX)) { // Exclusive lock fwrite($fp , "Write something here\n"); flock($fp , LOCK_UN); // release lock } else { echo "Couldn't lock the file!" ; } fclose($fp); Contin... Read PHP multiple threads reading, writing a file at the same time

Main Contents

Parallel processing in PHP using pcntl_fork() Explanation

The pcntl_fork() function is a function used to create a process in the php-pcntl module. (does not support windows).

As for how to install and enable the php_pcntl extension, I won’t introduce it here, only analyze the pcntl_fork() function itself.

When the pcntl_fork() function is executed, a child process will be created. The child process will copy everything of the current process, which is the parent process: data, code, and state.

1. When pcntl_fork() successfully creates a child process, it returns the child process number in the parent process, returns 0 in the child process, and returns -1 if it fails

2. The child process will copy the code and data of the parent process. Then it means: the code and data owned by the child and the parent process will be exactly the same.

3. Focus: The child process will copy the state of the parent process, then there is the above sample code: Execute pcntl_fork on the fifth line, then the created child process, the code is also executed from the fifth line. And the child process copied the data and code. Therefore, the same exists in the child process: $one, $two, and other variables.

So: How many child processes will actually be generated by the above for loop? The answer is 7. Under Linux, you can see 8 processes (1 parent process, 7 child processes) with the ps command.

Please Share This Article Thank You!

What is PHP, what can PHP do, why use PHP?

PHP (PHP: Hypertext Preprocessor recursive abbreviation) Chinese name is: "Hypertext Preprocessor ", is a widely used general-purpose open-source scripting language, suitable for Web site development, it can be embedded in...

7 Tips for PHP Performance Optimization

PHP is a very popular scripting language, and now many companies (Sina, Youku, Baidu, Sohu, Taobao, etc.) are using this language for website development. With this article of mine, I just hope to improve your PHP script p...