English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Básico de Comunicação de Processos do PHP através de Sinais

Para comunicação de sinais, você pode usar kill -l para verificar o tipo de sinal atual do sistema.
Para ver o significado detalhado de cada sinal, consulte este meu artigo: https://pt.oldtoolbag.com/article/106040.htm
Ao usar sinais, você pode verificar a versão atual do sistema de sinais usando php --Para verificar a versão atual do PHP, já decidiu qual método usar para comunicação de sinais entre processos.

[root@roverliang ipc]# php --versão
PHP 5.6.24 (cli) (construído: Ago 15 2016 19:14:02)
Copyright (c) 1997-2016 O Grupo PHP
Zend Engine v2.6.0, Copyright (c) 1998-2016 Zend Technologies

To use the pcntl_signal_dispatch function, the PHP version (PHP 5 >= 5.3.0, PHP 7)

If the PHP version is less than5.3. Some large companies may be below this version. At this time, declare(ticks=1), meaning that each time a low-level instruction is executed,
it will check whether the signal occurs. Detailed introduction can be viewed at https://pt.oldtoolbag.com/article/48340.htm

The official explanation is as follows: Tick (clock cycle) is an event that occurs when the interpreter executes N countable low-level statements in the declare code block. The value of N is specified in the directive part of declare with ticks=N.

What are low-level statements? As shown in the following code:

  for ($i = 0; $i < 3; $i++) {
    echo $i.PHP_EOL;
  }

Then this for loop contains three low-level instructions. Each time $i is output, it will check whether an event has occurred that has been registered. As you can imagine, this efficiency is relatively low. So if the PHP version is greater than or equal to5.3 So use pcntl_singal_dispath to perform signal dispatch.

The main process registers some signal handling functions when it starts.

/**
 * @param $signal Signal
 */
function signalHandal($signal)
{
  switch ($signal) {
    case SIGINT:
      //do something
      break;
    case SIGHUP:
      //do something
      break;
    default :
      //do something
      break;
  }
}

Then bind the signal handler to the signal processing function:

//Install different signal handlers based on different signals
pcntl_signal(SIGINT, 'signalHandal');
pcntl_signal(SIGHUP, 'signalHandal');
pcntl_signal(SIGUSR1, 'signalHandla');

Listen to the signal in the child process, if the signal occurs, call the pre-installed signal handling function

//Signal allocation.
pcntl_signal_dispatch($signal);

Let's organize our thoughts:
1Define the function that needs to be processed for the occurrence of the signal
2Binding the signal and the signal processing function, called signal installation.
3Signal listening or distribution, a signal is called for the installed signal.

Understand the concept of the above signal, let's see a demo:

<?php
$parentpid = posix_getpid();
echo "parent progress pid:{$parentpid}\n";
//Define uma função manipuladora de sinal
function sighandler($signal) {
  if ($signal == SIGINT) {
    $pid = getmypid();
    exit("{$pid} process, Killed!".PHP_EOL);
  }
}
//php version < 5.3 . Verifica se o sinal foi gerado após cada instrução de baixo nível. Isso resulta em uma grande perda de eficiência.
//declare(ticks=1);
$child_list = [];
//Registra um manipulador de sinal. Quando o sinal for emitido, chama a função definida
pcntl_signal(SIGINT, 'sighandler');
for($i = 0; $i < 3; $i++) {
  $pid = pcntl_fork();
  if ($pid == 0) {
    //Subprocesso
    while (true) {
      //Chama o manipulador de sinais instalado para detectar se há novos sinais aguardando dispatching
      pcntl_signal_dispatch();
      echo "I am child: ".getmypid(). " and i am running !".PHP_EOL;
      sleep(rand(1,3));
    }
  }
    $child_list[] = $pid;
  } else {
    die('fork fail!'.PHP_EOL);
  }
}
sleep(5);
foreach ($child_list as $key => $pid) {
  posix_kill($pid, SIGINT);
}
sleep(2);
echo "{$parentpid} parent is end".PHP_EOL;
Você Também Pode Gostar