Home > Backend Development > PHP Tutorial > PHP daemon process. Add the linux command nohup to execute the task once per second_PHP tutorial

PHP daemon process. Add the linux command nohup to execute the task once per second_PHP tutorial

WBOY
Release: 2016-07-21 15:26:47
Original
1541 people have browsed it

The function of the nohup command in Unix is ​​to run the command without hanging up. At the same time, nohup puts all the output of the program into the nohup.out file in the current directory. If the file is not writable, it is placed in the /nohup.out in the file. So with this command, we can write PHP as a shell script and use a loop to keep our script running. No matter whether our terminal window is closed or not, our PHP script can keep running.
Write a PHP applet immediately. The function is to record time every 30 seconds and write it to a file

Copy the code The code is as follows:

# vi for_ever.php
#! /usr/local/php/bin/php
define('ROOT', dirname(__FILE__).'/');
set_time_limit(0 );
while (true) {
file_put_contents(ROOT.'for_ever.txt', date('Y-m-d H:i:s')."n", FILE_APPEND);
echo date('Y-m-d H:i:s'), ' OK!';
sleep(30);
}
?>

Save and exit, and then make the for_ever.php file available Execution permission:
# chmod +x for_ever.php
Let it execute in the background:
# nohup /home/andy/for_ever.php.php &
Remember to add the & symbol at the end, like this Only then can you run it in the background.
After executing the above command, the following prompt appears:
[1] 5157
nohup: appending output to 'nohup.out'
All command execution output information will be placed in nohup .out file
At this time, you can open for_ever.txt and nohup.out in the same directory as for_ever.php to see the effect!
Okay, it will run forever, how to end it?
# ps
PID TTY TIME CMD
4247 pts/1 00:00:00 bash
5157 pts/1 00:00:00 for_ever.php
5265 pts/1 00:00 :00 ps
# kill -9 5157
Find the process number 5157 and kill it, you will see
[1]+ Killed nohup /home/andy/for_ever.php
OK!
====================
In many projects, there may be many similar back-end scripts that need to be executed regularly through crontab. For example, check the user status every 10 seconds. The script is as follows:
@file: /php_scripts/scan_userstatus.php
Copy the code The code is as follows:

#!/ usr/bin/env php -q
$status = has_goaway();
if ($status) {
//done
}
?>

Execute the script scan_userstatus.php regularly through crontab
#echo “*:*/10 * * * * /php_scripts/scan_userstatus.php”
In this way, the script will be executed every 10 seconds.
We found that within a short period of time, the memory resources of the script had not been released, and a new script was enabled. In other words: the new script is started, but the resources occupied by the old script have not been released as expected. In this way, a lot of memory resources are wasted over time. We have made some improvements to this script, and the improvements are as follows:
@file: /php_scripts/scan_userstatus.php
Copy the code The code is as follows:

#/usr/bin/env php -q
while (1) {
$status = has_goaway();
if ($status) {
//done
}
usleep(10000000);
}
?>

In this way, crontab is no longer needed. You can execute the script through the following command to achieve the same functional effect
#chmod +x /php_scripts/scan_userstatus.php
#nohup /php_scripts/scan_userstatus.php &
Here, we put the script through & Running in the background, in order to prevent the process from being killed when the terminal session window is closed, we use the nohup command. So is there any way to run it without using the nohup command, just like the Unin/Linux Daemon? Next, is the daemon function we are going to talk about.
What is a daemon? A daemon is usually thought of as a background task that does not control the terminal. It has three distinctive features: it runs in the background, is separated from the process that started it, and does not need to control the terminal. The commonly used implementation method is fork() -> setsid() -> fork(). The details are as follows:
@file: /php_scripts/scan_userstatus.php
Copy code The code is as follows:

#/usr/bin/env php -q
daemonize();
while (1) {
$status = has_goaway( );
if ($status) {
//done
}
usleep(10000000);
}
function daemonize() {
$pid = pcntl_fork() ;
if ($pid === -1 ) {
return FALSE;
} else if ($pid) {
usleep(500);
exit(); //exit parent
}
chdir("/");
umask(0);
$sid = posix_setsid();
if (!$sid) {
return FALSE;
}
$pid = pcntl_fork();
if ($pid === -1) {
return FALSE;
} else if ($pid) {
usleep(500 );
exit(0);
}
if (defined('STDIN')) {
fclose(STDIN);
}
if (defined('STDOUT') ){
fclose(STDOUT);
}
if (defined('STDERR')) {
fclose(STDERR);
}
}
?>

After implementing the daemon process function, you can create a resident process, so you only need to execute it once:
#/php_scripts/scan_userstatus.php
The two more critical php functions here are pcntl_fork() and posix_setsid(). Forking () a process means creating a copy of the running process. The copy is considered a child process, and the original process is considered the parent process. After fork() is run, it can be separated from the process and terminal control that started it, which also means that the parent process can exit freely. The return value of pcntl_fork(), -1 indicates execution failure, 0 indicates that it is in the child process, and the return process ID number indicates that it is in the parent process. Here, exit the parent process. setsid(), it first makes the new process become the "leader" of a new session, and finally makes the process no longer control the terminal. This is also the most critical step in becoming a daemon process, which means that it will not be forced when the terminal is closed. Exit the process. This is a critical step for a resident process that cannot be interrupted. Perform the last fork(). This step is not necessary, but it is usually done. Its greatest significance is to prevent the control terminal from being obtained. (When a terminal device is opened directly and the O_NOCTTY flag is not used, the control terminal will be obtained).
Other instructions:
1) chdir() puts the daemon process in a directory that always exists, Another benefit is that your resident process does not restrict you from umounting a file system.
2)umask() sets the file mode and creates a mask to the maximum allowed limit. If a daemon needs to create a file with readable and writable permissions, an inherited mask with stricter permissions will have the opposite effect.
3) fclose(STDIN), fclose(STDOUT), fclose(STDERR) closes the standard I/O stream. Note that the daemon will fail if there is output (echo). Therefore, STDIN, STDOUT, and STDERR are usually redirected to a specified file.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/323870.htmlTechArticleThe function of nohup command in Unix is ​​to run the command without hanging up. At the same time, nohup puts all the output of the program into the current In the directory nohup.out file, if the file is not writable, it will be placed in the user homepage...
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template