PHP uses PCNTL and libevent to implement the timer function _php Tutorial

Source: Internet
Author: User
Tags php error signal handler
PHP uses PCNTL and libevent to implement the timer function, first look at the example, Pcntl (PHP thread) explained below.
Copy CodeThe 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, verify: CSL, interested can join in the 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 extension Pcntl implements "multithreading" (process)
Pcntl and Ticks
Ticks is defined by the Declare (ticks = N) {statement} syntax, and declare syntax is currently only accepted ticks, and the meaning of ticks = n defined by declare is that when n-low-level statements are executed in the specified block of statements, An event that can be registered by Register_tick_function ($function _name).
The signal mechanism of PCNTL is based on the ticks mechanism. Therefore, we need to increase the declare (ticks = n) syntax structure before we use the signal-related functions in the Pcntl family function.
int pcntl_alarm (int $seconds):
A SIGALRM signal is sent to the process after $seconds seconds, and the previously set clock is canceled each time the Pcntl_alarm method is called.
void Pcntl_exec (String $path [, array $args [, array $env]]:
Executes a program in the current process space.
$path: Must be a binary executable, or a script file path with valid script header information (#!/usr/local/bin/php).
$args: List of string arguments to be passed to the program (array form)
$envs: Environment variables. Passed to the environment variable to execute the program in the form of an array (key = value).
int pcntl_for k (void):
Creates a child process that differs from the parent process only as a PID (process number) and PPID (parent process number).
When the parent thread executes, it returns the child process PID that was created, returns 0 when the child thread executes, and returns 1 in the parent process context when the child process fails, and throws a PHP error.
Understand the fork here need to know: Pcntl_fork creates a branch node, equivalent to a token, the parent process is completed, the child process will continue to execute from the mark, that is, the code after the Pcntl_fork by the parent process and the child process is executed two times, and two processes in the The return values that are obtained during the row are different. Therefore, the parent-child process can be detached to execute different code.
int pcntl_getpriority ([int $pid = Getmypid () [, int $process _identifier = prio_process]]):
Gets the priority of the process for the given $pid, by default the value obtained through Getmypid () is the current process.
$pid: If not specified, the default is the current process.
$process _identifier:prio_pgrp, Prio_user, prio_process one of the three, the default prio_process. Where PRIO_PGRP refers to the priority of getting a process group, prio_user refers to the priority of getting a user process, prio_process refers to getting a specific process priority.
Returns the priority of a process, or 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]]:
Sets the priority of the process.
$priority: Priority value, in the range 20 to 20, with the default priority of 0. A smaller value indicates a higher priority.
$pid: If not specified, refers to the current process
$process _identifier: Meaning $process _identifier with pcntl_getpriority.
The setting returns TRUE successfully, and the failure returns FALSE.
BOOL Pcntl_signal_dispatch (void):
Call the processor that is installing the incoming signal through pcntl_signal ().
The call returns TRUE successfully, and the failure returns false.
PHP 5.3.3 Join
BOOL Pcntl_signal (int $signo, callback $handler [, bool $restart _syscalls = True]):
Installs 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, remove, or set a lock signal, depending on $how parameters
$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 a given list of signals.
$set: To add, remove, or set the list of signals.
$oldset: Used to return the old lock signal to the caller.
The success returns TRUE, and the failure returns FALSE.
int pcntl_sigtimedwait (array $set [, Array & $siginfo [, int $seconds = 0[, int $nanoseconds = 0]]):
Pcntl_sigtimedwait actually did the same thing as Pcntl_sigwaitinfo (), but Pcntl_sigtimedwait has two more enhanced parameters $seconds and $nanoseconds, allowing the script to The dwell time has an upper limit rather than unlimited waiting.
$set: List of signals to wait
$siginfo: Information that is used to return the awaited signal to the caller, as shown in Pcntl_sigwaitinfo
$seconds: Number of seconds to timeout
$nanoseconds: Number of nanoseconds to timeout
After success, Pcntl_sigtimedwiat () returns the signal number
int Pcntl_sigwaitinfo (array $set [, Array & $siginfo]):
Suspends execution of the current script until a signal in the $set is received, and if one of the signals is to be reached (e.g. locked by pcntl_sigprocmask) then Pcntl_sigwaitinfo will return immediately
$set: List of waiting signals
$siginfo: The information that is used to return a waiting signal to the caller that contains the following content:
1. All signals have the following three messages:
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: Send process ID
e) UID: The real user ID of the sending process
3. Sigill, SIGFPE, SIGSEGV, Sigbus-owned information
A) Addr: the memory location that caused the failure
4. Sigpoll-Specific information:
A) Band:band event, meaning unknown
b) FD: File descriptor
function successfully run return signal number
int pcntl_wait (int & $status [, int *options = 0]):
Suspends the current process until a child process exits or until a signal is required to terminate the current process or call a signal handler. If a child process has exited at the time of invocation (known as a zombie process), the function returns immediately and all system resources are freed.
$status is used to hold state information for a child process, which is generated by the following function: pcntl_wifexited, pcntl_wifstopped, pcntl_wifsignaled, Pcntl_wexitstatus, Pcntl_ Wtermsig, Pcntl_wstopsig.
$options: If your system allows WAIT3 (most BSD class systems), you can provide an optional options parameter, and if you do not provide this parameter, wait will use the system call and 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 child process that exits, or returns 1 on error, or if Wnohang is provided as option (Wait3 unavailable system) and no valid child process returns 0
Zombie Process: Because the parent process cannot predict when the child process will end up after it has been forked, the child process leaves a data structure called a zombie, waiting for the parent process to initiate a wait operation to bury it, at the end of the child process (logical end) to the parent process, in order to leave some information to the parent process This period of time before the corpse process is called a zombie process, at the end of the parent process, all child processes are left to the Init to be responsible, so if the parent process ends, the zombie process will be recycled, but if the parent process never ends, these zombie processes will always occupy the process number, if the system process number Is exhausted, the new process cannot be started, so it is safe to bury the child processes that are generated for themselves in the parent process.
int pcntl_waitpid (int $pid, int & $status [, int $options = 0]):
Suspends the current process until a child process of a given $pid exits, or the current process receives an exit signal, or receives a IGE signal to invoke a signal processor.
If the corresponding child process for a given $pid has exited (zombie state) when calling this function, the function returns immediately and all system resources are freed.
$pid: Process number, less than 1 indicates that any child processes in the process group are waiting, and the process group number is the absolute value of the $pid. Equals-1 indicates waiting for any forbidden City, consistent with the pcntl_wait function behavior. equals 0 represents a child process that waits in the same group as the calling process, and greater than 0 represents a particular process.
$status: Used to return a child process state by a function. This state information is generated by the following functions: Pcntl_wifexited, pcntl_wifstopped, pcntl_wifsignaled, Pcntl_wexitstatus, Pcntl_wtermsig, Pcntl_ Wstopsig.
$options: The same meaning as the $options of pcntl_wait
int pcntl_wexitstatus (int $status):
Returns a child process return code that has been interrupted, which is useful only if the pcntl_wifexited function returns TRUE.
The $status parameter is the state information generated by the pcntl_waitpid.
BOOL pcntl_wifexited (int $status):
Checks whether a given state indicates that the child process exited normally.
BOOL pcntl_wifsignaled (int $status):
Checks whether a given state indicates that the child process was exited because it received a signal.
BOOL pcntl_wifstopped (int $status):
Checks whether the $status can indicate that the child process is currently stopped, and that the function is valid only if the wuntraced used by the Pcntl_waitpid function is the value of the $options parameter.
int pcntl_wstopsig (int $status):
By parsing the $status returns the number of the signal that causes the child process to stop, which is only valid if pcntl_wifsignaled returns TRUE.
int pcntl_wtermsig (int $status):
Returns the signal number that caused the process to break. This function is valid only if pcntl_wifsignaled returns TRUE.

http://www.bkjia.com/PHPjc/824924.html www.bkjia.com true http://www.bkjia.com/PHPjc/824924.html techarticle PHP uses PCNTL and libevent to implement the timer function, first look at the example, Pcntl (PHP thread) explained below. Copy the code 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.