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

Source: Internet
Author: User
Tags 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, put it in <用户主目录> The/nohup.out file. So with this command, we're going to write a shell script that uses loops to keep our scripts running, whether our terminal window is off or not, to keep our PHP script running.
Write a PHP applet at once, with a function of recording time every 30 seconds, writing to a file
Copy CodeThe 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 the exit, and then give the for_ever.php file executable permissions:
# chmod +x for_ever.php
Let it execute in the background again:
# nohup/home/andy/for_ever.php.php &
Remember to add & symbols at the end to run 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 the Nohup.out file
At this point you can open the for_ever.php with the 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 it and 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 by crontab timing. Like checking the user status every 10 seconds. The script is as follows:
@file:/php_scripts/scan_userstatus.php
Copy CodeThe code is as follows:
#!/usr/bin/env Php-q
$status = Has_goaway ();
if ($status) {
Done
}
?>

Execute scripts with crontab timing scan_userstatus.php
#echo "*:*/10 * * * */php_scripts/scan_userstatus.php"
This will execute the script every 10 seconds.
We found that in a short period of time, the script's memory resources were not released and new scripts were enabled. That is: The new script is started, and the resources used by the old script are not released as intended. So, over time, a lot of wasted memory resources. We have made some improvements to this script, as follows:
@file:/php_scripts/scan_userstatus.php
Copy CodeThe code is as follows:
#/usr/bin/env Php-q
while (1) {
$status = Has_goaway ();
if ($status) {
Done
}
Usleep (10000000);
}
?>

This way, there is no need for crontab. You can execute the script 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 in the background through &, in order to prevent the Terminal session window shutdown process from being killed, we used the Nohup command. Then there is no way, do not make Nohup command, also can run, just like Unin/linux daemon. Next, we're going to talk about the daemon function.
What is a daemon? A daemon usually complements a background task that does not control the terminal. It has three distinct features: running in the background, disconnected from the startup process, and without the need to control the terminal. The common implementation is fork (), Setsid (), fork () in detail as follows:
@file:/php_scripts/scan_userstatus.php
Copy CodeThe 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);
}
}
?>

Once the daemon function has been implemented, a resident process can be established so that only one time is required:
#/php_scripts/scan_userstatus.php
The more critical two PHP functions here are pcntl_fork () and Posix_setsid (). Fork () is a process that creates a copy of the running process, which is considered a child process, and the original process is considered a parent process. When fork () runs, it can be detached from initiating his process and terminal control, and also means that the parent process is free to exit. The Pcntl_fork () return value, 1 indicates that the execution failed, 0 is in the child process, and the return process ID number is represented in the parent process. Here, quit the parent process. Setsid (), which first makes the new process the "leader" of a session, and finally makes the process no longer control the terminal, which is the most critical step in becoming a daemon, which means that the process will not be forced to quit as the terminal shuts down. This is a critical step for a permanent process that will not be interrupted. The last fork (), this step is not necessary, but usually do so, its greatest significance is to prevent access to the control terminal. (The control terminal is obtained when a terminal device is opened directly, and the O_NOCTTY flag is not used).
Other Notes:
1) chdir () put the daemon in a directory that always exists, and another benefit is that your resident process does not limit your umount to a filesystem.
2) Umask () sets the file mode, creating a 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) Close the standard I/O stream. Note that if there is an output (echo), the daemon fails. Therefore, stdin, STDOUT, stderr are usually redirected to 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.