search
HomeBackend DevelopmentPHP TutorialHow to use pcntl and libevent in PHP to implement Timer function

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";  
}

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!

Statement
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
How do you modify data stored in a PHP session?How do you modify data stored in a PHP session?Apr 27, 2025 am 12:23 AM

TomodifydatainaPHPsession,startthesessionwithsession_start(),thenuse$_SESSIONtoset,modify,orremovevariables.1)Startthesession.2)Setormodifysessionvariablesusing$_SESSION.3)Removevariableswithunset().4)Clearallvariableswithsession_unset().5)Destroythe

Give an example of storing an array in a PHP session.Give an example of storing an array in a PHP session.Apr 27, 2025 am 12:20 AM

Arrays can be stored in PHP sessions. 1. Start the session and use session_start(). 2. Create an array and store it in $_SESSION. 3. Retrieve the array through $_SESSION. 4. Optimize session data to improve performance.

How does garbage collection work for PHP sessions?How does garbage collection work for PHP sessions?Apr 27, 2025 am 12:19 AM

PHP session garbage collection is triggered through a probability mechanism to clean up expired session data. 1) Set the trigger probability and session life cycle in the configuration file; 2) You can use cron tasks to optimize high-load applications; 3) You need to balance the garbage collection frequency and performance to avoid data loss.

How can you trace session activity in PHP?How can you trace session activity in PHP?Apr 27, 2025 am 12:10 AM

Tracking user session activities in PHP is implemented through session management. 1) Use session_start() to start the session. 2) Store and access data through the $_SESSION array. 3) Call session_destroy() to end the session. Session tracking is used for user behavior analysis, security monitoring, and performance optimization.

How can you use a database to store PHP session data?How can you use a database to store PHP session data?Apr 27, 2025 am 12:02 AM

Using databases to store PHP session data can improve performance and scalability. 1) Configure MySQL to store session data: Set up the session processor in php.ini or PHP code. 2) Implement custom session processor: define open, close, read, write and other functions to interact with the database. 3) Optimization and best practices: Use indexing, caching, data compression and distributed storage to improve performance.

Explain the concept of a PHP session in simple terms.Explain the concept of a PHP session in simple terms.Apr 26, 2025 am 12:09 AM

PHPsessionstrackuserdataacrossmultiplepagerequestsusingauniqueIDstoredinacookie.Here'showtomanagethemeffectively:1)Startasessionwithsession_start()andstoredatain$_SESSION.2)RegeneratethesessionIDafterloginwithsession_regenerate_id(true)topreventsessi

How do you loop through all the values stored in a PHP session?How do you loop through all the values stored in a PHP session?Apr 26, 2025 am 12:06 AM

In PHP, iterating through session data can be achieved through the following steps: 1. Start the session using session_start(). 2. Iterate through foreach loop through all key-value pairs in the $_SESSION array. 3. When processing complex data structures, use is_array() or is_object() functions and use print_r() to output detailed information. 4. When optimizing traversal, paging can be used to avoid processing large amounts of data at one time. This will help you manage and use PHP session data more efficiently in your actual project.

Explain how to use sessions for user authentication.Explain how to use sessions for user authentication.Apr 26, 2025 am 12:04 AM

The session realizes user authentication through the server-side state management mechanism. 1) Session creation and generation of unique IDs, 2) IDs are passed through cookies, 3) Server stores and accesses session data through IDs, 4) User authentication and status management are realized, improving application security and user experience.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.