PHP uses pcntl and libevent to implement Timer function _ PHP Tutorial

Source: Internet
Author: User
Tags php error
PHP uses pcntl and libevent to implement the Timer function. PHP uses pcntl and libevent to implement the Timer function. let's take a look at the example. the pcntl (PHP thread) is explained below. Copy the code as follows :? PhpfunctionnewChild ($ func_name) {echoenternew PHP uses pcntl and libevent to implement the Timer function. let's look at the example. the pcntl (PHP thread) is explained below.

The code is as follows:



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: ^ _ ^ good php Development Exchange Group: 256271784, verification: csl. if you are interested, join in for discussion)
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 "Multithreading" (process)
Pcntl and ticks
Ticks is defined through the declare (ticks = n) {statement} syntax. Currently, the declare syntax can only accept ticks, the ticks = n defined by declare indicates that when N low-level statements are executed in the specified statement block in declare, an event can be registered through register_tick_function ($ function_name.
The signal mechanism of pcntl is implemented based on the ticks mechanism. Therefore, we need to add the declare (ticks = n) syntax structure before using the function related to signals in pcntl family functions.
Int pcntl_alarm (int $ seconds ):
$ Seconds sends a SIGALRM signal to the process in seconds. 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 have valid script header information (#! /Usr/local/bin/php) script file path.
$ Args: List of string parameters to be passed to the program (in array form)
$ Envs: environment variable. the environment variable passed to the program to be executed in the form of an array (key => value.
Int pcntl_for k (void ):
Create a sub-process. The sub-process and the parent process are only PID (process number) and PPID (parent process number.
The pid of the created child process is returned during execution of the parent thread, and 0 is returned during execution of the child thread. if the child process fails to be created,-1 is returned in the context of the parent process, and a php error is thrown.
To understand the fork, you need to know that pcntl_fork creates a branch node, which is equivalent to a tag. after the parent process is complete, the child process continues to run from the tag, that is to say, the code after pcntl_fork is executed twice by the parent process and the child process respectively, and the returned values of the two processes are different during execution. therefore, the parent and child processes can be separated to execute different code.
Int pcntl_getpriority ([int $ pid = getmypid () [, int $ process_identifier = PRIO_PROCESS]):
Gets the priority of the process corresponding to the given $ pid. the default value is the value obtained through getmypid (), that is, the current process.
$ Pid: If not specified, the current process is used by default.
$ Process_identifier: PRIO_PGRP, PRIO_USER, and PRIO_PROCESS. the default value is PRIO_PROCESS. PRIO_PGRP indicates the priority of the process Group, PRIO_USER indicates the priority of the user process, and PRIO_PROCESS indicates the priority of the specified.
Return the priority of the process, or return false when an error occurs. the higher the value, the higher the preference.
Bool pcntl_setpriority (int $ priority [, int $ pid = getmypid () [, int $ process_identifier = PRIO_PROCESS]:
Sets the priority of a process.
$ Priority: priority value in the range of-20 to 20. the default priority is 0.
$ Pid: If not specified, it indicates the current process
$ Process_identifier: $ process_identifier of pcntl_getpriority.
If the setting succeeds, TRUE is returned. if the setting fails, FALSE is returned.
Bool pcntl_signal_dispatch (void ):
Call the processor of the upcoming signal installed through pcntl_signal.
If the call is successful, TRUE is returned. if the call fails, false is returned.
Php 5.3.3 added
Bool pcntl_signal (int $ signo, callback $ handler [, bool $ restart_syscils = 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]):
Add, delete, or set the lock signal. the specific behavior depends on the $ how parameter.
$ How: SIG_BLOCK is used to increase 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 replace the current lock signal with the given signal list.
$ Set: List of signals to be added, removed, or set.
$ Oldset: used to return the old lock signal to the caller.
TRUE is returned for success, FALSE is returned for 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, in this way, there is an upper limit on the stay time of the script instead of unlimited waiting.
$ Set: List of signals to wait
$ Siginfo: used to return the waiting signal information to the caller. for details, see pcntl_sigwaitinfo.
$ Seconds: timeout seconds
$ Nanoseconds: the number of seconds that have timed out
After the call succeeds, pcntl_sigtimedwiat () returns the signal number.
Int pcntl_sigwaitinfo (array $ set [, array & $ siginfo]):
Suspend the execution of the current script until a signal in $ set is received. if one of the signals is about to arrive (for example, it is locked by pcntl_sigprocmask), pcntl_sigwaitinfo will return immediately
$ Set: waiting signal list
$ Siginfo: used to return the information of the waiting signal to the caller. This information includes the following content:
1. all signals have the following information:
A) signo: signal number
B) errno: error code
C) code: Signal code
2. unique SIGCHLD signal information
A) status: exit value or signal
B) utime: time consumed by users
C) stime: time consumed by the system
D) pid: id of the sending process
E) uid: the real user id of the sending process
3. information owned by SIGILL, SIGFPE, SIGSEGV, and SIGBUS
A) addr: memory location where the fault occurs
4. unique SIGPOLL information:
A) band: band event, meaning unknown
B) fd: file descriptor
Signal number returned when the function runs successfully
Int pcntl_wait (int & $ status [, int * options = 0]):
Suspends the current process until a sub-process exits or until a signal is required to terminate the current process or call a signal processing function. if the sub-process has exited (commonly known as a zombie process) during the call, this function will return immediately and all system resources will be released.
$ Status is used to save the status information of sub-processes. this status information is generated by the following functions: running, pcntl_wifstopped, pcntl_wifsignaled, pcntl_wexitstatus, pcntl_wtermsig, and pcntl_wstop.
$ Options: If your system allows wait3 (most BSD 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 not affect you. the value of $ options can be two constants: 0, WNOHANG, and WUNTRACED.
The function returns the PID of The exited sub-process, or-1 in case of an error, or if WNOHANG is provided as the option (wait3 unavailable system) and no valid sub-process returns 0.
Zombie process: because the parent process cannot predict when the child process ends after fork, the child process will leave a data structure called a botnet to leave some information to the parent process, wait for the parent process to initiate a wait operation to send a zombie to the child process. after the child process ends (the logic ends) and ends to the parent process, the child process is called a Zombie process, after the parent process ends, all child processes are handled by Init. Therefore, if the parent process ends, the zombie process is recycled. However, if the parent process never ends, these zombie processes keep occupying the process number. if the system process number is exhausted, the new process cannot be started. therefore, it is safe to collect dead parts for the child process generated by the parent process.
Int pcntl_waitpid (int $ pid, int & $ status [, int $ options = 0]):
Suspend the current process until the child process with a 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 $ pid has exited (zombie state) when calling this function, the function returns immediately and all system resources are released.
$ Pid: Process Number. if it is less than-1, it indicates that any sub-process in the process group is waiting, and the process group number is the absolute value of $ pid. -1 indicates waiting for any Forbidden City, which is consistent with the behavior of the pcntl_wait function. if the value is equal to 0, it indicates that the child process is waiting in the same group as the calling process. if the value is greater than 0, it indicates a specific process.
$ Status: returned by the function. this status information is generated by the following functions: running, pcntl_wifstopped, pcntl_wifsignaled, pcntl_wexitstatus, pcntl_wtermsig, and pcntl_wstopsig.
$ Options: it has the same meaning as pcntl_wait's $ options.
Int pcntl_wexitstatus (int $ status ):
Returns the code returned by an interrupted sub-process. This function is only useful when the pcntl_wifexited function returns TRUE.
$ Status indicates the status information generated by pcntl_waitpid.
Bool pcntl_wifexited (int $ status ):
Check whether the specified status indicates that the sub-process exits normally.
Bool pcntl_wifsignaled (int $ status ):
Check whether the specified status indicates that the sub-process exits because it receives a signal.
Bool pcntl_wifstopped (int $ status ):
Check whether $ status indicates that the sub-process has been stopped. This function is valid only when WUNTRACED acting on the pcntl_waitpid function is used as the value of $ options.
Int pcntl_wstopsig (int $ status ):
Returns the number of the signal that causes the sub-process to stop by analyzing $ status. This function is valid only when pcntl_wifsignaled returns TRUE.
Int pcntl_wtermsig (int $ status ):
Returns the number of signals that interrupt the process. This function is valid only when pcntl_wifsignaled returns TRUE.

The http://www.bkjia.com/PHPjc/824924.htmlwww.bkjia.comtruehttp://www.bkjia.com/PHPjc/824924.htmlTechArticlePHP uses pcntl and libevent to implement the Timer function. let's take a look at the example. the pcntl (PHP thread) is explained below. The code is as follows :? Php function newChild ($ func_name) {echo "enter new...

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.