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

Jul 21, 2016 pm 03:26 PM
linux nohup php unix Task Function add Order accomplish implement process

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...
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1666
14
PHP Tutorial
1273
29
C# Tutorial
1252
24
Which of the top ten currency trading platforms in the world are among the top ten currency trading platforms in 2025 Which of the top ten currency trading platforms in the world are among the top ten currency trading platforms in 2025 Apr 28, 2025 pm 08:12 PM

The top ten cryptocurrency exchanges in the world in 2025 include Binance, OKX, Gate.io, Coinbase, Kraken, Huobi, Bitfinex, KuCoin, Bittrex and Poloniex, all of which are known for their high trading volume and security.

Docker on Linux: Containerization for Linux Systems Docker on Linux: Containerization for Linux Systems Apr 22, 2025 am 12:03 AM

Docker is important on Linux because Linux is its native platform that provides rich tools and community support. 1. Install Docker: Use sudoapt-getupdate and sudoapt-getinstalldocker-cedocker-ce-clicotainerd.io. 2. Create and manage containers: Use dockerrun commands, such as dockerrun-d--namemynginx-p80:80nginx. 3. Write Dockerfile: Optimize the image size and use multi-stage construction. 4. Optimization and debugging: Use dockerlogs and dockerex

The Compatibility of IIS and PHP: A Deep Dive The Compatibility of IIS and PHP: A Deep Dive Apr 22, 2025 am 12:01 AM

IIS and PHP are compatible and are implemented through FastCGI. 1.IIS forwards the .php file request to the FastCGI module through the configuration file. 2. The FastCGI module starts the PHP process to process requests to improve performance and stability. 3. In actual applications, you need to pay attention to configuration details, error debugging and performance optimization.

What happens if session_start() is called multiple times? What happens if session_start() is called multiple times? Apr 25, 2025 am 12:06 AM

Multiple calls to session_start() will result in warning messages and possible data overwrites. 1) PHP will issue a warning, prompting that the session has been started. 2) It may cause unexpected overwriting of session data. 3) Use session_status() to check the session status to avoid repeated calls.

Top 10 Global Virtual Currency Exchange Rankings Top 10 Latest Virtual Currency APPs in 2025 Top 10 Global Virtual Currency Exchange Rankings Top 10 Latest Virtual Currency APPs in 2025 Apr 22, 2025 pm 02:39 PM

Top 10 global virtual currency exchanges rankings: 1. OKX, 2. Binance, 3. Gate.io, 4. Huobi, 5. Coinbase, 6. Kraken, 7. Bitfinex, 8. KuCoin, 9. Bybit, 10. Bitstamp, these platforms provide real-time market trends, technical analysis tools and user-friendly interfaces to help investors conduct effective market analysis and trading decisions.

How to understand DMA operations in C? How to understand DMA operations in C? Apr 28, 2025 pm 10:09 PM

DMA in C refers to DirectMemoryAccess, a direct memory access technology, allowing hardware devices to directly transmit data to memory without CPU intervention. 1) DMA operation is highly dependent on hardware devices and drivers, and the implementation method varies from system to system. 2) Direct access to memory may bring security risks, and the correctness and security of the code must be ensured. 3) DMA can improve performance, but improper use may lead to degradation of system performance. Through practice and learning, we can master the skills of using DMA and maximize its effectiveness in scenarios such as high-speed data transmission and real-time signal processing.

How to handle high DPI display in C? How to handle high DPI display in C? Apr 28, 2025 pm 09:57 PM

Handling high DPI display in C can be achieved through the following steps: 1) Understand DPI and scaling, use the operating system API to obtain DPI information and adjust the graphics output; 2) Handle cross-platform compatibility, use cross-platform graphics libraries such as SDL or Qt; 3) Perform performance optimization, improve performance through cache, hardware acceleration, and dynamic adjustment of the details level; 4) Solve common problems, such as blurred text and interface elements are too small, and solve by correctly applying DPI scaling.

macOS vs. Linux: Exploring the Differences and Similarities macOS vs. Linux: Exploring the Differences and Similarities Apr 25, 2025 am 12:03 AM

macOSandLinuxbothofferuniquestrengths:macOSprovidesauser-friendlyexperiencewithexcellenthardwareintegration,whileLinuxexcelsinflexibilityandcommunitysupport.macOS,developedbyApple,isknownforitssleekinterfaceandecosystemintegration,whereasLinux,beingo

See all articles