Home > Backend Development > PHP Tutorial > How to use pcntl and libevent in PHP to implement Timer function

How to use pcntl and libevent in PHP to implement Timer function

不言
Release: 2023-04-01 11:08:01
Original
1777 people have browsed it

The Timer function is implemented in PHP, and PHP multi-threading is used in the middle. This article gives an explanation of pcntl.

PHP uses pcntl and libevent to implement the Timer function. Let’s look at the example first. pcntl (PHP thread) is explained below.

<?php  
function newChild($func_name) {  
    echo "enter newChild\n";  
    $args = func_get_args();  
    unset($args[0]);  
    $pid =  pcntl_fork();  
    if ($pid == 0) {  
        function_exists($func_name) and exit(call_user_func_array($func_name, $args)) or exit(-1);  
    } else if($pid == -1) {  
        echo "Couldn&#39;t create child process";  
    } else {  
        return $pid;  
    }  
}  
(PS:^_^不错的php开发交流群:256271784,验证:csl,有兴趣的话可以加入进来一起讨论)
function on_timer() {  
    echo "timer called\n";  
}  
   
/** 
 * @param $func string, function name 
 * @param $timeouts int, microtimes for time delay 
 */ 
function timer($func, $timeouts){  
   
    echo "enter timer\n";  
    $base = event_base_new();  
    $event = event_new();  
   
    event_set($event, 0, EV_TIMEOUT, $func);  
    event_base_set($event, $base);  
    event_add($event, $timeouts);  
   
    event_base_loop($base);  
}  
   
$pid = newChild("timer", "on_timer", 5000000);  
   
if ($pid > 0) {  
    echo "master process exit\n";  
}
Copy after login

PHP extends pcntl to implement "multi-threading" (process)
pcntl and ticks
ticks are defined through declare(ticks = n) {statement} syntax. The declare syntax can currently only accept ticks. He defines The meaning of ticks = n is that an event occurs when N low-level statements are executed in the statement block specified by declare. This event can be registered through register_tick_function($function_name).
The signal mechanism of pcntl is implemented based on the ticks mechanism . Therefore, when we use signal-related functions in the pcntl family of functions, we need to add the declare(ticks = n) syntax structure in front.
int pcntl_alarm(int $seconds):
$seconds seconds to send a SIGALRM signal, each call to the pcntl_alarm method will cancel the previously set clock.
void pcntl_exec(string $path[, array $args[, array $env]]):
Execute a program in the current process space.
$path: Must be a binary executable file, or a script file path with valid script header information (#!/usr/local/bin/php).
$args: String arguments to be passed to the program List (array form)
$envs: environment variables. Pass to the environment variables of the program to be executed in the form of array (key => value form).
int pcntl_for k (void):
Create a child Process, the child process is different from the parent process only in PID (process number) and PPID (parent process number).
Returns the created child process pid when the parent thread is executed, returns 0 when the child thread is executed, and creates a child process When it fails, -1 will be returned in the context of the parent process and a php error will be triggered.
To understand the fork here, you need to know: pcntl_fork creates a branch node, which is equivalent to a mark. After the parent process is completed, the child process will start from the mark. Continue execution, that is to say, the code after pcntl_fork is executed twice by the parent process and the child process respectively, and the return values ​​obtained by the two processes during execution are different. Therefore, the parent and child processes can be separated to execute different codes.
int pcntl_getpriority([int $pid = getmypid()[, int $process_identifier = PRIO_PROCESS]]):
Get the priority of the process corresponding to the given $pid. The default value is obtained through getmypid(). It is the current process.
$pid: If not specified, the default is the current process.
$process_identifier: One of PRIO_PGRP, PRIO_USER, PRIO_PROCESS, the default is PRIO_PROCESS. Among them, PRIO_PGRP refers to the priority of obtaining the process group, and PRIO_USER refers to Get the priority of the user process. PRIO_PROCESS refers to getting the priority of a specific process.
Return the priority of the process, or return false when an error occurs. The smaller the value, the higher the priority.
bool pcntl_setpriority(int $priority[, int $pid = getmypid()[, int $process_identifier = PRIO_PROCESS]]:
Set the priority of the process.
$priority: priority value, in the range of -20 to 20, the default priority is 0. Value The smaller the value, the higher the priority.
$pid: If not specified, refers to the current process
$process_identifier: The meaning is the same as pcntl_getpriority's $process_identifier.
Returns TRUE if set successfully, and FALSE if failed.
bool pcntl_signal_dispatch( void):
Call the handler of the upcoming signal installed through pcntl_signal().
Return TRUE if the call is successful, false if it fails.
php 5.3.3 Add
bool pcntl_signal(int $signo , callback $handler[, bool $restart_syscalls = true]):
Install a new signal handler $handler for the specified signal $signo.
The last parameter does not understand the meaning.
bool pcntl_sigprocmask(int $how, array $set[, array &$oldset]):
Add, delete or set the lock signal, the specific behavior depends on the $how parameter
$how: SIG_BLOCK is used to add the signal to the current lock signal Among them, SIG_UNBLOCK is used to remove the signal from the current lock signal, and SIG_SETMASK is used to replace the current lock signal with the given signal list.
$set: The signal list to be added, removed or set.
$ oldset: used to return the old lock signal to the caller.
Returns TRUE on success, FALSE on failure.
int pcntl_sigtimedwait(array $set[, array &$siginfo[, int $seconds = 0[, int $ nanoseconds = 0]]]):
pcntl_sigtimedwait actually does the same thing as pcntl_sigwaitinfo(), but pcntl_sigtimedwait has two more enhanced parameters $seconds and $nanoseconds, which allows the script to have a dwell time of Upper limit instead of unlimited waiting.
$set: List of signals that need to be waited for
$siginfo: Used to return information to the caller about the signal to be waited for. For information content, see pcntl_sigwaitinfo
$seconds: Seconds for timeout Number
$nanoseconds: The number of nanoseconds for timeout
After success, pcntl_sigtimedwiat() returns the signal number
int pcntl_sigwaitinfo(array $set[, array &$siginfo]):
Suspend the current script Executed until a signal in $set is received. If one of the signals is about to arrive (for example, locked by pcntl_sigprocmask), then pcntl_sigwaitinfo will return immediately
$set: waiting signal list
$siginfo: used Returns to the caller the information of the signal waiting for the signal, which includes the following content:
1. All signals have the following three pieces of information:
a) signo: signal number
b) errno: error number
c) code: signal code
2. SIGCHLD signal-specific information
a) status: exit value or signal
b) utime: user consumption time
c) stime: system consumption time
d) pid: sending process id
e) uid: real user id of sending process
3. Information owned by SIGILL, SIGFPE, SIGSEGV, SIGBUS
a) addr: memory location where the fault occurred
4. SIGPOLL unique information:
a) band: band event, meaning unknown
b) fd: file descriptor
The function returns the signal number after successful operation
int pcntl_wait(int &$status[ , int *options = 0]):
Hang the current process until a child process exits or until a signal requires the current process to be terminated or a signal handling function is called. If the child process has exited when called (commonly known as a zombie process ), this function will return immediately, and all system resources will be released.
$status is used to save the status information of the child process. The status information is generated by the following functions: pcntl_wifexited, pcntl_wifstopped, pcntl_wifsignaled, pcntl_wexitstatus, pcntl_wtermsig, pcntl_wstopsig .
$options: If your system allows wait3 (most BSD-like systems), you can provide an optional options parameter. If this parameter is not provided, wait will use the system call. If the system does not allow wait3 , providing this parameter will have no effect, the value of $options can be 0 or the two constants WNOHANG and WUNTRACED.
The function returns the PID of the exiting child process, or -1 on error, or if WNOHANG is provided as option(wait3 unavailable system) and there is no valid child process returns 0
Zombie process: Since the parent process is after fork, it is impossible to predict when the child process will end, so in order to leave some information to the parent process, the child process will leave The next data structure called a zombie waits for a wait operation initiated by the parent process to collect its corpse. The child process is called a zombie process during the period between the end of the child process (logical end) and the collection of its corpse by the parent process. After the end, all child processes will be handed over to Init. Therefore, if the parent process ends, the zombie processes will be recycled. However, if the parent process never ends, these zombie processes will always occupy the process number. If the system process number is exhausted, If it is exhausted, it will result in the inability to start a new process. Therefore, the safe way is to collect the corpses of the child processes generated by itself in the parent process.
int pcntl_waitpid(int $pid, int &$status[, int $options = 0 ]):
Suspend the current process until the child process with the given $pid exits, or the current process receives an exit signal, or receives an ige signal to call a signal handler.
If $pid is given The corresponding child process has exited (zombie state) when this function is called. The function returns immediately and all system resources are released.
$pid: process number, less than -1 indicates that it is waiting for any child process in the process group , the process group number is the absolute value of $pid. Equal to -1 means waiting for any Forbidden City, consistent with the behavior of the pcntl_wait function. Equal to 0 means waiting for a child process in the same group as the calling process, and greater than 0 means it is a specific process.
$status: used to return the child process status from the function. This status information is generated by the following functions: pcntl_wifexited, pcntl_wifstopped, pcntl_wifsignaled, pcntl_wexitstatus, pcntl_wtermsig, pcntl_wstopsig.
$options: has the same meaning as the $options of pcntl_wait
int pcntl_wexitstatus (int $status):
Returns an interrupted child process return code. This function is only useful when the pcntl_wifexited function returns TRUE.
The $status parameter is the status information generated by pcntl_waitpid.
bool pcntl_wifexited(int $status):
Check whether the given status indicates that the child process exited normally.
bool pcntl_wifsignaled(int $status):
Check whether the given status indicates that the child process exited due to receiving a certain signal .
bool pcntl_wifstopped(int $status):
Check whether $status can indicate that the child process is currently stopped. This function only generates $status when acting on WUNTRACED used by the pcntl_waitpid function as the value of the $options parameter. Only valid.
int pcntl_wstopsig(int $status):
Returns the number of the signal that stops the child process by analyzing $status. This function is only valid when pcntl_wifsignaled returns TRUE.
int pcntl_wtermsig(int $status):
Returns the signal number that interrupts the process. This function is only valid when pcntl_wifsignaled returns TRUE.

The above is the entire content of this article, I hope it will be helpful to everyone's learning, more Please pay attention to the PHP Chinese website for related content!

Related recommendations:

Analysis of the differences between ceil, floor, round and intval of PHP rounding functions

How to use curl in PHP to simulate post uploading and receiving files

##

The above is the detailed content of How to use pcntl and libevent in PHP to implement Timer function. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template