Explanation of Operation Code of PHP Signal Processing Mechanism

  • 2021-12-09 08:20:33
  • OfStack

Let's first look at the example code:


function sig_handler($sig)

{

  print("handled sig: $sig\n");

}

 

 

 

pcntl_signal(SIGIO,  "sig_handler");

posix_kill(posix_getpid(),SIGIO);

 

while(true)

{

  posix_kill(posix_getpid(),SIGIO);

 

  pcntl_signal_dispatch();

 

  sleep(1);

}

It is better to process the signal queue manually and cyclically, instead of using the signal processing mechanisms such as declare (ticks=1) and tick_handler () provided by php. Because of the performance problems of tick mechanism, every statement executed calls back tick_handler to see if there is a signal, but there is no signal for a large part of the time.

posix_signal sets the callback processing of the signal,

posix_kill simply puts the signal into the signal waiting queue of the process, all does not trigger the signal callback, and pcntl_signal_dispatch processes the signal in the signal queue

posix_getpwnam ("nginx"): Gets uid, gid, and so on for the user name

pcntl_signal (SIGPIPE, SIG_IGN, false): Ignore the SIGPIPE signal sent by the kernel. When the connection has been closed, the process continues to send data to the invalid socket, and the system will receive TCP packet containing RST control bit. The system will send an SIGPIPE signal to the process, telling the process that the connection has been disconnected and don't write again. The default processing of this signal is to terminate the process, and the process can capture it and ignore the signal to avoid being unwillingly terminated.

socket Context Options:

backlog: Used to limit the number of outstanding connections in the flow listening queue

so_reuseport: Reuse port (the kernel schedules to connect to multiple processes listening on the same port, and the number of listening processes cannot be changed because the corresponding process is marked by hash)

Timer signal processing


pcntl_signal(SIGALRM,"sig_handler");

pcntl_alarm(2);

function sig_handler($sig)

{

  echo "one second after";

}

while (1)

{

  pcntl_signal_dispatch();

  sleep(1);

}


Related articles: