


How 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'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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

You can check which extensions are used by PHP by viewing the phpinfo() function output, using command line tools, and checking the PHP configuration file. 1. View the phpinfo() function output, create a simple PHP script, save this script as phpinfo.php, and upload it to your web server. Access this file in the browser and use the browser's search function. Just look for the keyword "extension" or "extension_loaded" on the page to find information about the extension.

How to use PHP to extend PDO to connect to Oracle database Introduction: PHP is a very popular server-side programming language, and Oracle is a commonly used relational database management system. This article will introduce how to use PHP extension PDO (PHPDataObjects) to connect to Oracle database. 1. Install the PDO_OCI extension. To connect to the Oracle database, you first need to install the PDO_OCI extension. Here are the steps to install the PDO_OCI extension: Make sure

How to use PHP to extend the report generation function of SuiteCRM SuiteCRM is a powerful open source CRM system that provides rich functions to help enterprises manage customer relationships. One of the important functions is report generation. Using reports can help enterprises better understand their business situations and make correct decisions. This article will introduce how to use PHP to extend the report generation function of SuiteCRM and provide relevant code examples. Before starting, you need to make sure that SuiteCRM is installed.

When developing with PHP, we may need to use some PHP extensions. These extensions can provide us with more functions and tools, making our development work more efficient and convenient. But before using these extensions, we need to install them first. This article will introduce you to how to install PHP extensions. 1. What is a PHP extension? PHP extensions refer to components that provide additional functionality and services to the PHP programming language. These components can be installed and used through PHP's extension mechanism. PHP extension can help us with

PHP is a popular server-side scripting language that can handle dynamic content on web pages. The geoip extension for PHP allows you to get information about the user's location in PHP. In this article, we’ll cover how to use PHP’s geoip extension. What is the GeoIP extension for PHP? The geoip extension for PHP is a free, open source extension that allows you to obtain data about IP addresses and location information. This extension can be used with the GeoIP database, a database developed by MaxMin

Pagoda Panel is an open source server management panel. While providing website operators with convenient website management, database management, SSL certificate management and other services, it also provides powerful PHP extension and PHP version management functions, making server management easier. Be more simple and efficient. 1. PHP extension PHP extension is a module used to enhance PHP functions. By installing PHP extensions, more functions and services can be implemented, such as: accelerator: accelerator can significantly improve PHP performance, and reduce service load by caching PHP scripts.

Common errors and solutions for fork failure in PHPPCNTL When using the PHPPCNTL extension for process management, you often encounter the problem of fork failure. Fork is a method of creating a child process. In some cases, the fork operation may fail due to some errors. This article will introduce some common fork failure errors and corresponding solutions, and provide specific code examples to help readers better understand and deal with these problems. 1. Possible error message for insufficient memory: Can

PHP extension development is the art of creating custom functionality, extending PHP core functionality and building more powerful applications. It opens up new possibilities in the PHP world, allowing developers to transcend the basic limitations of the language. This article will take you on a journey of PHP extension development, providing you with comprehensive knowledge and practical guidance from basic concepts to advanced techniques. PHP extension development basics Before starting PHP extension development, you need to understand some basic concepts. What are PHP extensions? A PHP extension is a dynamic link library (DLL) that extends PHP core functionality and provides new data types, functions and classes. Advantages of PHP Extensions PHP extensions have many advantages, including: scalability, flexibility, performance optimization, and code reuse. PHP
