Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the PHP multi-process programming?

2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article introduces the relevant knowledge of "what kind of PHP multi-process programming". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

1. Prepare for

Before you do it, make sure you're not using the M $Windows platform (because I don't have a Windows). Linux / BSD / Unix should be fine. After confirming the working environment, let's see if we have all the PHP modules we need. Open the terminal and enter the following command:

$php-m

This command checks and prints all the open extensions of the current PHP to see if pcntl and posix are in the output list.

1.1. Pcntl

If you can't find pcntl, you probably didn't compile this extension at the time of compilation. If you are compiling and installing PHP like me, then you need to recompile and install PHP. Remember to add the-- enable-pcntl parameter when configuring.

$cd / path/to/php_source_code_dir $. / configure [some other options]-- enable-pcntl$ make & & make install

1.2. Posix

This product will be installed by default, as long as you do not add-- disable-posix when compiling.

two。 Preliminary knowledge

Before you continue, you need to know a little bit about Linux multi-processes. What about multiple processes? This is a little different from the shadow avatar in Naruto. First of all, Naruto grew up from childhood to big, such as 16 years old, cough. One day he launched a shadow avatar and identified five of him. Obviously, these avatars are also 16-year-old Naruto rather than babies who cry when they are born without knowing anything (that's called cloning). Then there is something different: separate people become independent people to do their own things, and each other no longer know what the other parts and the original have done (of course, they do not accumulate experience to the original as they do in cartoons). Unless they communicate with each other, only the events before the age of 16 are their common memories.

A classmate said, boss, are you kidding me? I've never seen Naruto! Then you should go and have a look at it.

Finally, the preparatory knowledge is over, that is, to get a general idea of what is going on with the sub-process opened by the main process. The code of the child process is exactly the same as the main process, and part of the same thing is everything that is executed until the shadow avatar is started. See the operating system course for details.

3. The art of shadow separation

So, how can you understand the contents of the scroll without some basic knowledge? When you open the scroll, you first see a word: fork.

3.1. Fork

Fork? Forks are bifurcated, one becomes more than one! That's pretty much what it means. Use this command to create a child process. The pcntl_fork () function is needed here. You can first take a brief look at the introduction to this function in the PHP manual. ) create a PHP script:

$pid = pcntl_fork (); / / once the call is successful, things will be a little different. If ($pid = =-1) {die ('fork failed');} else if ($pid = = 0) {} else {}

The pcntl_fork () function creates a child process. The only difference between the child process and the parent process is that PID (process ID) and PPID (parent process ID) are different. Use the ps command to view the process under the terminal (ask man to see how to use ps: man ps). When the function returns a value of-1, fork fails. Try adding a sentence before if: echo $pid. PHP_EOL; . Run your script and the output might look like this (the result indicates that the code of the child process is the same as that of the parent process):

67789 # this is printed by the parent process 0 # this is printed by the child process

When the pcntl_fork () function is called successfully, the PID of the child process is returned in the parent process, while 0 is returned in the child process. So, let's directly use the if branch to control the parent and child processes to do different things.

3.2. Assign tasks

Then let's talk about Naruto's 16-year-old shadow split, assigning two simple output tasks to the original and the split:

$parentPid = getmypid (); / / this is the legendary memory before the age of 16$ pid = pcntl_fork (); / / once the call is successful, things will be a little different if ($pid = =-1) {die ('fork failed');} else if ($pid = = 0) {$mypid = getmypid (); / / use the getmypid () function to get the PID echo' I am child process. My PID is'of the current process. $mypid. ' And my father\'s PID is'. $parentPid. PHP_EOL;} else {echo'Oh my god! I am a father now! My child\'s PID is'. $pid. ' And mine is'. $parentPid. PHP_EOL;}

The result of the output might be like this:

Oh my god! I am a father now! My child's PID is 68066 and mine is 68065I am child process. My PID is 68066 and my father's PID is 68065

Again, after a successful call to pcntl_fork (), one program becomes two programs: one program gets the value of the $pid variable 0, which is a child process, and the other program gets a value of $pid greater than 0, which is the PID of the child process, which is the parent process. In the following branch statement, different code is run due to the difference in the value of $pid. Again: the code of the child process is the same as that of the parent process. So you have to assign them different tasks through branch statements.

3.3. Child process recovery

Was there a man ps just now? Generally, I am used to using ps aux plus grep command to find running background processes. There is a column of STAT that identifies the running status of each process. Here, we focus on status Z: Zombie. When the child process exits before the parent process, and the parent process does nothing to it, the child process will become a zombie process. Oops, it is different from the shadow avatar in Fire Shadow again. Naruto's shadow split automatically disappears after it is dried to death, but if the child process here dies, it still leaves an empty shell until the parent process reclaims it. Although the zombie process does not take up much memory, it is a nuisance to the eye, and the pile of zombies lying in the yard feels strange. (don't forget that they still occupy PID.)

In general, it is fine to recycle the hung child process before the parent process ends. There is a pcntl_wait () function in the pcntl extension that suspends the parent process until a child process exits. If a child process becomes a zombie, it will return immediately. All child processes have to be recycled, so it doesn't matter if you wait!

3.4. The parent process hung up first.

What if the parent process dies first? What will happen? Nothing will happen, and the child process is still running. But at this point, the child process is handed over to process 1, which becomes the stepparent of these child processes. Process 1 will handle the resources of these processes well, and process 1 will automatically reclaim resources when they are finished. So, another temporary way to deal with zombie processes is to shut down their parent process.

4. Signal

Generally speaking, the multi-process thing is over, but the signal is really a very important thing in the system. A signal is a semaphore. When a semaphore is lit, the program will react. You must have used this, for example, to run a program under the terminal, but there is no response after waiting for a long time. Maybe you will press Ctrl+C to close the program. In fact, this is where the keyboard sends an interrupt signal to the program: SIGINT. Sometimes the process will execute the kill [PID] command when it loses its response, and without any other parameters, the program will receive a SIGTERM signal. When the program receives the above two signals, it will end execution by default, so is it possible to change this default behavior? It has to be possible!

4.1. Registration signal

People are living programs are also living, but the program needs to follow the rules made by people to run. Now start resetting the rules for the signal, and the function used here is pcntl_signal () (why not check the PHP manual before continuing? ). The following program will redefine the behavior of SIGINT. Watch out:

/ / define a processor that outputs only one line of information function signalHandler ($signal) {if ($signal = = SIGINT) {echo 'signal received'. PHP_EOL;}} / / signal registration: when receiving a SIGINT signal, call the signalHandler () function pcntl_signal (SIGINT, 'signalHandler'); while (true) {sleep (1); / / do something pcntl_signal_dispatch (); / / call the registered signalHandler ()} when the signal is received

Execute it and press Ctrl+C at any time to see what happens.

4.2. Signal distribution

To be clear: the pcntl_signal () function simply registers the signal and its processing method, and the one that really receives the signal and calls its processing method is the pcntl_signal_dispatch () function. Try replacing / / do something with the following code:

For ($I = 0; $I < 1000000; $iota +) {echo $I. PHP_EOL; usleep (100000);}

Execute the script under the terminal and try to press Ctrl+C when it keeps outputting numbers. See how the program responds? Um... There is nothing, except that there may be an extra ^ C on the screen, and the program keeps outputting numbers. Because the program never executes to pcntl_signal_dispatch (), there is no call to signalHandler (), so there is no output signal received.

4.3. Version problem

If you read the PHP document carefully, you will find that the function pcntl_signal_dispatch () is only supported by PHP 5.3. if your PHP version is greater than 5.3, it is recommended to use this method to call the signal processor. The following versions need to add a sentence before the registration signal: declare (ticks = 1); it means that every time a low-level instruction is executed, the signal is checked, and if the registered signal is detected, the signal processor is called. It's annoying to think about it. Why do you keep checking it? It would be better to check it at our designated place.

4.4. Feel the zombie process.

Now let's get back to the problem of child process recycling (almost forgot = "). When one of your child processes dies (or ends), but the parent process is still running and may not quit for a long time. A zombie process has stood up ever since! At this time, the Umbrella Company (kernel) found a zombie in its turf. Whose son is this zombie? Just take a look at PPID. The kernel then sends a signal to the PPID process (that is, the parent of the zombie process): SIGCHLD. Then, do you know how to recycle this child process in the parent process? As a hint, use the pcntl_wait () function.

4.5. Send a signal

I hope there has just been a serious man kill command. It actually sends a signal to the process, and the posix_kill () function can also be called in PHP to achieve the same effect. With it, you can control the operation of other child processes in the parent process. For example, if all child processes are closed before the end of the parent process, then the PID of all child processes is recorded in the parent process during fork, and the parent process sends end signals to the child process in turn before the end of the parent process.

5. Practice

The multi-process of PHP is quite similar to that of C, and it is more or less the same for words written in other languages in the future. If you have time, try writing a Mini Program and get a first-hand taste of it:

1. The 16-year-old Naruto sent a shadow split and divided into five avatars.

two。 Each individual randomly survives for 10 to 30 seconds and outputs something per second.

3. Ensure that the original body can feel the end of the split, and then start another one, ensuring that there are up to five separate bodies.

4. Do not use nohup, so that the original can still run after the terminal is closed.

5. Write the number of split parts (5) into a configuration file, and when sending a signal to the original (you can consider using SIGUSR1 or SIGUSR2), the original reads the configuration file and updates the maximum number of split parts allowed

6. If there are more parts, close a few; if there are fewer, divide a few more.

Tip:

1. Use the while loop to ensure that the process runs, and pay attention to sleep to avoid 100% CPU occupation

two。 When the terminal running the process is closed, the program receives a SIGHUP signal

3. You can parse the INI configuration file with the parse_ini_file () function

This is the end of the content of PHP multi-process programming. Thank you for your reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report