PHP daemon plus linux command nohup Implementation task _php instance per second

Source: Internet
Author: User
Tags chmod echo date php script stdin usleep
The nohup command function in UNIX is to run the command without hanging up, while nohup all output of the program to the current directory Nohup.out file, if the file is not writable, to the < user home directory >/nohup.out file. So with this command, we PHP is written as a shell script to use the loop to keep our scripts running, regardless of whether our terminal window is closed can let our PHP script continue to run.
Immediately write a PHP applet, the function for every 30 seconds recording time, write to the file
Copy Code code 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 exit, then give for_ever.php file executable permission:
# chmod +x for_ever.php
Let it run in the background again:
# nohup/home/andy/for_ever.php.php &
Remember the final plus & symbol, so that you can run to the background to run
After you perform the above command, you receive the following prompt:
[1] 5157
nohup:appending output to ' nohup.out '
All command execution output information will be placed in the Nohup.out file
At this time you can open for_ever.php with the directory of For_ever.txt and nohup.out look at the effect!
Well, 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 process number 5157 kill, you will see
[1]+ killed nohup/home/andy/for_ever.php
Ok!
====================
In many projects, there may be a lot of similar back-end scripts that need to be executed through crontab timing. For example, check the user status every 10 seconds. The script is as follows:
@file:/php_scripts/scan_userstatus.php
Copy Code code as follows:

#!/usr/bin/env Php-q
$status = Has_goaway ();
if ($status) {
Done
}
?>

Script execution via crontab scan_userstatus.php
#echo "*:*/10 * * */php_scripts/scan_userstatus.php"
That way, every 10 seconds, the script is executed.
We found that, in a short time, the script's memory resources had not been released, and new scripts were enabled. That is, the new script is started and the resources used by the old script have not been released. So, accumulated over time, wasted a lot of memory resources. We've made some improvements to this script, and the improvements are as follows:
@file:/php_scripts/scan_userstatus.php
Copy Code code as follows:

#/usr/bin/env Php-q
while (1) {
$status = Has_goaway ();
if ($status) {
Done
}
Usleep (10000000);
}
?>

In this way, no need for crontab. The script can be executed with the following command to achieve the same functional effect
#chmod +x/php_scripts/scan_userstatus.php
#nohup/php_scripts/scan_userstatus.php &
Here, we run the script through &, and we use the Nohup command to prevent the end session window from being killed in the shutdown process. Then there is no way, not to make Nohup command, also can run, just like Unin/linux daemon. Next, that's the daemon function we're going to talk about.
What is a daemon? A daemon usually complements a background task that is not controlled by the terminal. It has three distinct features: running in the background, disengaging from the process that started him, without having to control the terminal. The common implementation is fork ()-> setsid ()-> fork () in detail as follows:
@file:/php_scripts/scan_userstatus.php
Copy Code code 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 you implement the Daemon function, you can establish a resident process, so you only need to do it once:
#/php_scripts/scan_userstatus.php
The more critical two PHP functions are pcntl_fork () and Posix_setsid (). Fork () a process, it means that a copy of the running process is created, that the replica is considered a child process, and that the original process is considered a parent process. When fork () is run, it can be detached from the process and terminal control that started him, and it means that the parent process is free to quit. Pcntl_fork () Returns the value,-1 indicates execution failure, 0 is in the subprocess, and the process ID number is represented in the parent process. Here, exit the parent process. Setsid (), which first makes the new process a "leader" of the session, and finally stops the process from controlling the terminal, is also the most critical step in becoming a daemon, which means that the process will not be forced out as the terminal closes. This is a critical step for a resident process that will not be interrupted. For the last time fork (), this step is not necessary, but it is usually done, and its greatest significance is to prevent the acquisition of control terminals. (A control terminal is obtained when a terminal device is directly opened and the O_NOCTTY flag is not used).
Other Matters Description:
1 chdir () put the daemon in a directory that always exists, and the other advantage is that your resident process will not limit your umount to a filesystem.
2 Umask () sets the file mode to create the mask to the maximum allowable limit. If a daemon needs to create a file with readable, writable permissions, an inherited mask with more restrictive permissions can be counterproductive.
3) fclose (STDIN), fclose (STDOUT), fclose (STDERR) closes the standard I/O stream. Note that if there is output (echo), the daemon fails. So typically stdin, STDOUT, and stderr redirect a specified file.

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.