В этой статье описывается создание и работа подпроцесса в модуле процессов PHP spool. Подробности заключаются в следующем:
Swoogle предоставляет нам модуль управления процессами process для замены расширения pcntl PHP, который удобен для нас для создания процессов, управления процессами и взаимодействия между процессами.
Катушка обеспечивает два вида связи между процессами
1. Труба на основе сокета UNIX.
2. Очередь сообщений на основе sysvmsg.
Мы можем использовать новую катушку? Процесс () Быстро создайте процесс. По умолчанию носок? Dgram будет создан Тип канала, используемый для межпроцессной связи, конечно, может быть установлен на другие типы, также не может быть создан.
1, Межпроцессная связь через синхронный блокирующий конвейер
php $worker_process_nums = 5; $worker_process = []; for ($i = 0; $i < $worker_process_nums; $i++) { //Create child process //The default is to create a pipeline for each child process. If you do not want to create a pipeline, set $pipe_ The type parameter is false //Note that the default pipeline is synchronous blocking, half duplex, if you can not read the data will block $worker = new swoole_process(function (swoole_process $worker) { //Note that if the main process does not write the data write (), then the child process will block the read () here $task = json_decode($worker->read(), true); //Carry out the calculation task $tmp = 0; for ($i = $task['start']; $i < $task['end']; $i++) { $tmp += $i; } Echo 'subprocess PID:', $worker - > PID, 'calculation', $task ['Start '],' - ', $task ['end'],'result: ', $TMP, PHP_ EOL; //Write the calculated results to the pipeline $worker->write($tmp); //Subprocess exit $worker->exit(); }); //Save child process $worker_process[$i] = $worker; //Start child process $worker->start(); } //Posts tasks to each subprocess pipeline for ($i = 0; $i < $worker_process_nums; $i++) { $worker_process[$i]->write(json_encode([ 'start' => mt_rand(1, 10), 'end' => mt_rand(50, 100), ])); } //The parent process monitors the exit signal of the child process, recycles the child process, and prevents the zombie process swoole_process::signal(SIGCHLD, function ($sig) { //Must be false, non blocking mode while ($ret = swoole_process::wait(false)) { Echo "subprocess PID: {$RET ['pid ']} quits from the system; } });
2、 Через катушку? Событие? Добавьте Сделать канал асинхронным для связи
pipe, function ($pipe) use ($worker) { $task = json_decode($worker->read(), true); $tmp = 0; for ($i = $task['start']; $i < $task['end']; $i++) { $tmp += $i; } Echo "subprocess: {$worker - > PID} compute {$task ['Start ']} - {$task ['end']} n '; //The subprocess writes the result of calculation into the pipeline $worker->write($tmp); //Attention, spool_ event_ Add and spool_ event_ Del should be used in pairs swoole_event_del($worker->pipe); //Exit subprocess $worker->exit(); }); }); $worker_process[$i] = $worker; //Start child process $worker->start(); } for ($i = 0; $i < $worker_process_nums; $i++) { $worker = $worker_process[$i]; $worker->write(json_encode([ 'start' => mt_rand(1, 10), 'end' => mt_rand(50, 100), ])); //In the main process, listen to the sub process pipeline events swoole_event_add($worker->pipe, function ($pipe) use ($worker) { $result = $worker->read(); Echo "subprocess: {$worker - > PID} calculation result {$result} n"; swoole_event_del($worker->pipe); }); } //The parent process monitors the exit signal of the child process, recycles the child process, and prevents the zombie process swoole_process::signal(SIGCHLD, function ($sig) { //Must be false, non blocking mode while ($ret = swoole_process::wait(false)) { Echo "subprocess PID: {$RET ['pid ']} quits from the system; } });
3、 Использование очереди сообщений для завершения межпроцессной связи
pop(), true); $tmp = 0; for ($i = $task['start']; $i < $task['end']; $i++) { $tmp += $i; } Echo "subprocess: {$worker - > PID} compute {$task ['Start ']} - {$task ['end']} n '; $worker->push($tmp); $worker->exit(); }, false, false); //Use message queue as communication between processes //Note that message queuing is shared $worker->useQueue(); $worker_process[$i] = $worker; //Start child process $worker->start(); } for ($i = 0; $i < $worker_process_nums; $i++) { //Only one child process is needed to send the message, because the message queue is shared $worker_process[0]->push(json_encode([ 'start' => mt_rand(1, 10), 'end' => mt_rand(50, 100), ])); } //Note that you need to pause here to prevent the tasks that join the queue from being read out by the main process immediately. sleep(1); for ($i = 0; $i < $worker_process_nums; $i++) { $result = $worker_process[0]->pop(); Echo "calculated result: {$result} n"; } //The parent process monitors the exit signal of the child process, recycles the child process, and prevents the zombie process swoole_process::signal(SIGCHLD, function ($sig) { //Must be false, non blocking mode while ($ret = swoole_process::wait(false)) { Echo "subprocess PID: {$RET ['pid ']} quits from the system; } });
4, Процесс может контролировать сигнал через сигнал и устанавливать таймер с сигналом тревоги.
Мы можем установить сигнал прослушивания для родительского процесса, и когда дочерний процесс завершится, мы можем снова приостановить дочерний процесс.
Вы также можете установить таймер с помощью процесса spool_:: Kill ($PID, 0); определить, регулярно ли выполняется процесс.
10) { //Clear timer swoole_process::alarm(-1); } }); swoole_process::signal(SIGINT, function ($signo) { Echo "I was hit by Ctrl + C '; //Exit the main process, otherwise it will not exit normally exit(0); });
Для получения дополнительной информации о PHP читатели, интересующиеся им, могут ознакомиться со следующими темами: краткое описание навыков сетевого программирования PHP, краткое описание использования сокетов PHP, вводный курс объектно-ориентированного программирования PHP, учебник по структуре и алгоритму данных PHP, а также краткое описание алгоритма программирования PHP
Я надеюсь, что эта статья будет полезна для программирования на PHP.