Home > Article > PHP Framework > How swoole resides in the process
There are often scenarios like this in the backend. A certain script needs to be run repeatedly. At this time, it is best to have a daemon to help us continuously and automatically pull up These script processes allow it to run repeatedly automatically.
Swoole's process management module provides the function of inter-process communication, which can realize the automatic restart function of child processes. In swoole we can implement resident processes through process daemons.
To realize the protection of subprograms, two things need to be done:
1. The program needs to listen to the end signal of the subprocess in order to restart a new subprocess. .
2. The running environment of the child process needs to be independent of the parent process.
swoole process management module provides a bool Process->exec(string $execfile, array $args) method, which allows the child process to transform into another system call program, while also ensuring that the parent process is consistent with the current process. It is still a parent-child process relationship.
Then use the array Process::wait(bool $blocking = true) method to wait for the exit signal of the child process.
The following is a sample code that uses swoole to start a subprocess and recycle subprocess resources:
<?phpuse Swoole\Process; $php = "/usr/bin/env php"; $script = dirname(__DIR__) . "/task.php"; $command = "{$php} {$script}"; $process = new Process(function (Process $worker) use ($command) { $worker->exec('/bin/sh', ['-c', $command]); }); $pid = $process->start(); printf("启动子进程 {$pid}\n");while ($ret = Process::wait()) { $pid = intval($ret["pid"] ?? 0); printf("子进程 {$pid} 结束\n"); }
Code analysis:
$command variable indicates that a subprocess script is required, through exec () method to start running as a sub-process, and then use Process::wait() to wait for the $command sub-process script to end and recycle process resources.
Then, as long as you start the same sub-process script after receiving the end signal of the sub-process, you can realize the guardianship of the sub-process. Therefore, the first program implementation code to protect the child process:
<?php use Swoole\Process; $php = "/usr/bin/env php"; $script = dirname(__DIR__) . "/task.php"; $command = "{$php} {$script}"; do { $process = new Process(function (Process $worker) use ($command) { $worker->exec('/bin/sh', ['-c', $command]); }); $pid = $process->start(); printf("启动子进程 {$pid}\n"); } while (Process::wait());
Code analysis:
This code only adds the logic of starting the child process to an infinite loop, so that the child can Process scripts can be restarted continuously.
Recommended learning: swoole video tutorial
The above is the detailed content of How swoole resides in the process. For more information, please follow other related articles on the PHP Chinese website!