Home Backend Development PHP Tutorial PHP uses pcntl and libevent to implement Timer function

PHP uses pcntl and libevent to implement Timer function

Dec 22, 2016 pm 04:13 PM

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 currently only accepts ticks, and the meaning of ticks = n he defines 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 based on the ticks mechanism. Therefore, we use the pcntl family function When adding signal-related functions, you need to add the declare(ticks = n) syntax structure in front.
int pcntl_alarm(int $seconds):
$seconds will send a SIGALRM signal to the process after
$seconds seconds. Each time the pcntl_alarm method is called, the previous setting will be cancelled. 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 have valid script header information (#!/usr/local/bin/php) script file path.
$args: String parameter list (array form) to be passed to the program
$envs: Environment variables. In the form of an array (key => value form) is passed to the environment variable of the program to be executed.
int pcntl_for k (void):
Create a child process, which is different from the parent process only in PID (process number) and PPID (parent process number).
in When the parent thread executes, it returns the pid of the created child process. When the child thread executes, it returns 0. When the child process fails to be created, it returns -1 in the parent process context and triggers a php error.
To understand the fork here, you need to know: pcntl_fork creates A branch node is equivalent to a mark. After the parent process is completed, the child process will continue to execute from the mark. That is to say, the code after pcntl_fork is executed twice by the parent process and the child process respectively, and the two processes get The return values ​​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 corresponding value of the given $pid The priority of the process, the default value obtained through getmypid() 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 getting the priority of the process group, PRIO_USER refers to getting the priority of the user process, and PRIO_PROCESS refers to getting the priority of a specific process.
Returns the priority of the process, or returns 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, default priority It is 0. The smaller the value, the higher the priority.
$pid: If not specified, it refers to the current process.
$process_identifier: The meaning is the same as pcntl_getpriority's $process_identifier.
Returns TRUE if the setting is successful, and returns FALSE if it fails.
bool pcntl_signal_dispatch(void):
Call the handler of the upcoming signal installed through pcntl_signal().
The call returns TRUE on success, false on failure.
php 5.3.3 added
bool pcntl_signal(int $signo, callback $handler[, bool $restart_syscalls = true] ):
Install a new signal processor $handler for the specified signal $signo.
The last parameter does not understand the meaning.
bool pcntl_sigprocmask(int $how, array $set[, array &$oldset]):
Increase, 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, SIG_UNBLOCK is used to remove the signal from the current lock signal, SIG_SETMASK is used to use the given The signal list replaces the current lock signal.
$set: The list of signals 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 allow the script to have an upper limit on the dwell time instead of waiting indefinitely.
$set: a list of signals that need to be waited for
$siginfo: used to return to the caller information about the signals to be waited for , see pcntl_sigwaitinfo for information content
$seconds: Number of seconds for timeout
$nanoseconds: Number of nanoseconds for timeout
After success, pcntl_sigtimedwiat() returns the signal number
int pcntl_sigwaitinfo(array $set[, array &$siginfo]):
Hang Start the execution of the current script until a signal in $set is received. If one of the signals is about to arrive (such as being 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 contains 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 time spent
c) stime: system time spent
d) pid: sending process id
e ) uid: The real user ID of the sending process
3. Information owned by SIGILL, SIGFPE, SIGSEGV, SIGBUS
a) addr: The memory location where the fault occurred
4. SIGPOLL-specific information:
a) band: band event, meaning unknown
b)                                                                                                                                                                                                                                                                                                   process or call a signal processing function. 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 , this 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 exited child process PID, or returns -1 on error, or if WNOHANG is provided as option (system where wait3 is not available) 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. Therefore, in order to leave some information to the parent process, the child process will leave a data structure called a zombie, waiting for the parent process to initiate a wait operation to collect its corpse. After the child process ends (logical end) and the parent process collects its corpse, it will After a period of time, the child process is called a zombie process. After the parent process ends, 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, it will make it impossible to start a new process. Therefore, the safe way is to collect the corpses of the child processes it spawns in the parent process.
int pcntl_waitpid(int $pid , int &$status[, int $options = 0]):
Hang 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 the child process corresponding to the given $pid has exited (zombie state) when calling this function, the function returns immediately and all system resources are released.
$pid: process number, less than -1 indicates that the process is waiting For any child process in the group, the process group number is the absolute value of $pid. Equal to -1 indicates waiting for any Forbidden City, consistent with the behavior of the pcntl_wait function. Equal to 0 indicates waiting for a child process in the same group as the calling process, and greater than 0 indicates a specific process.
$status: used to return the child process status from the function. The 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 pcntl_wait's $options
int pcntl_ wexitstatus (int $status):
Returns the return code of an interrupted child process. 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 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 is only valid when acting on $status generated when the pcntl_waitpid function uses WUNTRACED as the value of the $options parameter.
int pcntl_wstopsig(int $status):
Through analysis $status returns the signal number that caused the child process to stop. This function is only valid when pcntl_wifsignaled returns TRUE.
int pcntl_wtermsig(int $status):
Returns the signal number that caused the process to interrupt. This function is only valid when pcntl_wifsignaled returns TRUE. Effective.

For more PHP related articles on using pcntl and libevent to implement the Timer function, please pay attention to the PHP Chinese website!

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

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1268
29
C# Tutorial
1246
24
PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

Explain secure password hashing in PHP (e.g., password_hash, password_verify). Why not use MD5 or SHA1? Explain secure password hashing in PHP (e.g., password_hash, password_verify). Why not use MD5 or SHA1? Apr 17, 2025 am 12:06 AM

In PHP, password_hash and password_verify functions should be used to implement secure password hashing, and MD5 or SHA1 should not be used. 1) password_hash generates a hash containing salt values ​​to enhance security. 2) Password_verify verify password and ensure security by comparing hash values. 3) MD5 and SHA1 are vulnerable and lack salt values, and are not suitable for modern password security.

How does PHP handle file uploads securely? How does PHP handle file uploads securely? Apr 10, 2025 am 09:37 AM

PHP handles file uploads through the $\_FILES variable. The methods to ensure security include: 1. Check upload errors, 2. Verify file type and size, 3. Prevent file overwriting, 4. Move files to a permanent storage location.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

How does PHP type hinting work, including scalar types, return types, union types, and nullable types? How does PHP type hinting work, including scalar types, return types, union types, and nullable types? Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

The Enduring Relevance of PHP: Is It Still Alive? The Enduring Relevance of PHP: Is It Still Alive? Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

See all articles