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

PHP uses pcntl and libevent to implement Timer function_PHP tutorial

Jul 13, 2016 am 10:25 AM
pcntl php extension

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

Copy code The code is as follows:


function newChild($func_name) {
echo "enter newChildn";
$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”; : csl, if you are interested, you can join in and discuss)
function on_timer() {
echo "timer calledn";
}


/**
 * @param $func string, function name
 * @param $timeouts int, microtimes for time delay
 */
function timer($func, $timeouts){


echo "enter timern";
$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 exitn";
}

PHP extends pcntl to implement "multi-threading" (process)
pcntl and ticks
ticks through declare(ticks = n) {statement} 语法定义的 , declare 语法目前只能接受 ticks, 他定义的 ticks = n 的意义是当 declare 指定的语句块中执行了 N 条低级语句去发生一个事件 , 这个事件可以通过 register_tick_function($function_name) 来注册 .
pcntl 的信号机制是基于 ticks 机制实现的 . 因此 , 我们使用 pcntl 族函数中信号相关的函数时 , 需要在前面增加 declare(ticks = n) 语法结构 .
int pcntl_alarm(int $seconds):
$seconds 秒后向进程发送一个 SIGALRM 信号 , 每次调用 pcntl_alarm 方法都会取消之前设置的时钟 .
void pcntl_exec(string $path[, array $args[, array $env]]):
在当前进程空间执行一个程序 .
$path: 必须是二进制可执行文件 , 或具有有效脚本头信息 (#!/usr/local/bin/php) 的脚本文件路径 .
$args: 将要传递给该程序的字符串参数列表 ( 数组形式 )
$envs: 环境变量 . 以数组 (key => value 形式 ) 方式传递给要执行程序的环境变量 .
int pcntl_for k (void):
创建一个子进程 , 该子进程与父进程仅仅是 PID( 进程号 ) 和 PPID( 父进程号 ) 不同 .
在父线程执行时返回创建的子进程 pid, 在子线程执行时返回 0, 创建子进程失败时会在父进程上下文返回 -1, 并引发 php 错误 .
理解这里的 fork 需要知道 : pcntl_fork 创建的是一个分支节点 , 相当于一个标记 , 父进程完成后 , 子进程会从标记处继续执行 , 也就是说 pcntl_fork 后面的代码分别被父进程和子进程执行了两遍 , 而两个进程在执行过程中得到的返回值是不同的 . 因此 , 才可以分离父子进程执行不同的代码 .
int pcntl_getpriority([int $pid = getmypid()[, int $process_identifier = PRIO_PROCESS]]):
获取给定 $pid 对应的进程的优先级 , 默认是通过 getmypid() 获取到的值也就是当前进程 .
$pid: 如果没有指定 , 默认是当前进程 .
$process_identifier: PRIO_PGRP, PRIO_USER, PRIO_PROCESS 三者之一 , 默认 PRIO_PROCESS. 其中 PRIO_PGRP 指获取进程组的优先级 , PRIO_USER 指获取用户进程的优先级 , PRIO_PROCESS 指获取特定进程优先级 .
返回进程的优先级 , 或者在发生错误时返回 false, 值越小说明越优先
bool pcntl_setpriority(int $priority[, int $pid = getmypid()[, int $process_identifier = PRIO_PROCESS]]:
设置进程的优先级 .
$priority: 优先级值 , -20 到 20 的范围内 , 默认优先级为 0.   值越小说明越优先 .
$pid: 如果没有指定 , 指当前进程
$process_identifier: 意义同 pcntl_getpriority 的 $process_identifier.
设置成功返回 TRUE, 失败返回 FALSE.
bool pcntl_signal_dispatch(void):
调用通过 pcntl_signal() 安装的即将发生的信号的处理器 .
调用成功返回 TRUE, 失败返回 false.
php 5.3.3 加入
bool pcntl_signal(int $signo, callback $handler[, bool $restart_syscalls = true]):
为指定的信号 $signo 安装一个新的信号处理器 $handler.
最后一个参数不明白意义 .
bool pcntl_sigprocmask(int $how, array $set[, array &$oldset]):
增加 , 删除或设置锁信号 , 具体的行为依赖于 $how 参数
$how: SIG_BLOCK 用于把信号增加到当前锁信号中 , SIG_UNBLOCK 用于把信号从当前锁信号中移除 , SIG_SETMASK 用于用给定的信号列表替换当前锁信号 .
$set: 要增加 , 移除或设置的信号列表 .
$oldset: 用于向调用者返回旧的锁定信号 .
成功返回 TRUE, 失败返回 FALSE.
int pcntl_sigtimedwait(array $set[, array &$siginfo[, int $seconds = 0[, int $nanoseconds = 0]]]):
pcntl_sigtimedwait 实际上和 pcntl_sigwaitinfo() 所做的是同样的事情 , 不过 pcntl_sigtimedwait 多了两个增强的参数 $seconds 和 $nanoseconds, 这样就允许脚本的停留时间有一个上限而不是无限制等待 .
$set: 需要等待的信号列表
$siginfo: 用来向调用者返回等待得到的信号的信息 , 信息内容见 pcntl_sigwaitinfo
$seconds: 超时的秒数
$nanoseconds: 超时的纳秒数
成功后 , pcntl_sigtimedwiat() 返回信号编号
int pcntl_sigwaitinfo(array $set[, array &$siginfo]):
挂起当前脚本的执行 , 直到接受到 $set 中的某个信号 , 如果其中的一个信号将要到达 ( 比如被 pcntl_sigprocmask 锁定 ) 那么 pcntl_sigwaitinfo 将会立刻返回
$set: 等待的信号列表
$siginfo: 用来向调用者返回等待得到的信号的信息 , 该信息包含以下内容 :
1.       所有信号都有以下三个信息 :
a)        signo: 信号编号
b)        errno: 错误号
c)         code: 信号代码
2.       SIGCHLD 信号特有的信息
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 identity of the sending process User id
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 runs successfully and returns the signal number
int pcntl_wait(int &$status[, int *options = 0]):
Suspend the current process until a child The 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, which 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 classes system), 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 WNOHANG. and WUNTRACED two constants.
The function returns the PID of the exiting child process, or -1 on error, or 0 if WNOHANG is provided as option (wait3 unavailable system) and there is no valid child process
Zombie Process: Since the parent process cannot predict when the child process will end after forking, 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. It collects corpses. The period between the end of the child process (logical end) and the period before the death of the parent 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 end, 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 result in the inability to start a new process. Therefore, the safe way is to start the new process in the parent process. Collect the corpses of the child processes generated by yourself.
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 processor.
If the child process corresponding to the given $pid has exited (zombie state) when calling this function, the function returns immediately , all system resources are released.
$pid: process number, less than -1 indicates that it is waiting for any child process in the process group, and the process group number is the absolute value of $pid. Equal to -1 indicates that it is waiting for any Forbidden City, The behavior is consistent with the pcntl_wait function. Equal to 0 means waiting for the 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 function : pcntl_wifexited, pcntl_wifstopped, pcntl_wifsignaled, pcntl_wexitstatus, pcntl_wtermsig, pcntl_wstopsig.
$options: The same meaning as pcntl_wait’s $options
int pcntl_wexitstatus(int $status):
Returns an interrupted subroutine 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):
Checks 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 signal.
bool pcntl_wifstopped(int $status):
Check $status Whether it can indicate that the child process is currently stopped, this function is only effective when acting on the $status generated when the pcntl_waitpid function uses WUNTRACED as the value of the $options parameter.
int pcntl_wstopsig(int $status):
Passed Analyzing $status returns the number of the signal that caused the child process to stop. This function is only valid when pcntl_wifsignaled returns TRUE.
int pcntl_wtermsig(int $status):
Returns the number of the signal that caused the process to interrupt. This function is only available when pcntl_wifsignaled returns TRUE. Valid only when pcntl_wifsignaled returns TRUE.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/824924.htmlTechArticlePHP uses pcntl and libevent to implement the Timer function. Let’s look at the example first. pcntl (PHP thread) is explained below. Copy the code The code is as follows: ?php function newChild($func_name) { echo "enter new...
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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

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)

How to check which extensions are used in php How to check which extensions are used in php Aug 01, 2023 pm 04:13 PM

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 extend SuiteCRM's report generation capabilities using PHP How to extend SuiteCRM's report generation capabilities using PHP Jul 19, 2023 am 10:27 AM

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.

How to use php to extend PDO to connect to Oracle database How to use php to extend PDO to connect to Oracle database Jul 29, 2023 pm 07:21 PM

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

Getting Started with PHP: PHP Extension Installation Getting Started with PHP: PHP Extension Installation May 20, 2023 am 08:49 AM

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

How to use PHP's geoip extension? How to use PHP's geoip extension? Jun 01, 2023 am 09:13 AM

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

PHP extension and PHP version management of Pagoda Panel PHP extension and PHP version management of Pagoda Panel Jun 21, 2023 am 08:49 AM

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 PHP PCNTL Common errors and solutions for fork failure in PHP PCNTL Feb 28, 2024 am 11:06 AM

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

In-depth exploration of PHP extension development: Uncovering the behind-the-scenes secrets of PHP extension development In-depth exploration of PHP extension development: Uncovering the behind-the-scenes secrets of PHP extension development Feb 19, 2024 pm 11:40 PM

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

See all articles