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

PHP: An Introduction to the Server-Side Scripting Language PHP: An Introduction to the Server-Side Scripting Language Apr 16, 2025 am 12:18 AM

PHP is a server-side scripting language used for dynamic web development and server-side applications. 1.PHP is an interpreted language that does not require compilation and is suitable for rapid development. 2. PHP code is embedded in HTML, making it easy to develop web pages. 3. PHP processes server-side logic, generates HTML output, and supports user interaction and data processing. 4. PHP can interact with the database, process form submission, and execute server-side tasks.

Why Use PHP? Advantages and Benefits Explained Why Use PHP? Advantages and Benefits Explained Apr 16, 2025 am 12:16 AM

The core benefits of PHP include ease of learning, strong web development support, rich libraries and frameworks, high performance and scalability, cross-platform compatibility, and cost-effectiveness. 1) Easy to learn and use, suitable for beginners; 2) Good integration with web servers and supports multiple databases; 3) Have powerful frameworks such as Laravel; 4) High performance can be achieved through optimization; 5) Support multiple operating systems; 6) Open source to reduce development costs.

PHP vs. Python: Use Cases and Applications PHP vs. Python: Use Cases and Applications Apr 17, 2025 am 12:23 AM

PHP is suitable for web development and content management systems, and Python is suitable for data science, machine learning and automation scripts. 1.PHP performs well in building fast and scalable websites and applications and is commonly used in CMS such as WordPress. 2. Python has performed outstandingly in the fields of data science and machine learning, with rich libraries such as NumPy and TensorFlow.

What computer configuration is required for vscode What computer configuration is required for vscode Apr 15, 2025 pm 09:48 PM

VS Code system requirements: Operating system: Windows 10 and above, macOS 10.12 and above, Linux distribution processor: minimum 1.6 GHz, recommended 2.0 GHz and above memory: minimum 512 MB, recommended 4 GB and above storage space: minimum 250 MB, recommended 1 GB and above other requirements: stable network connection, Xorg/Wayland (Linux)

Choosing Between PHP and Python: A Guide Choosing Between PHP and Python: A Guide Apr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and the Web: Exploring its Long-Term Impact PHP and the Web: Exploring its Long-Term Impact Apr 16, 2025 am 12:17 AM

PHP has shaped the network over the past few decades and will continue to play an important role in web development. 1) PHP originated in 1994 and has become the first choice for developers due to its ease of use and seamless integration with MySQL. 2) Its core functions include generating dynamic content and integrating with the database, allowing the website to be updated in real time and displayed in personalized manner. 3) The wide application and ecosystem of PHP have driven its long-term impact, but it also faces version updates and security challenges. 4) Performance improvements in recent years, such as the release of PHP7, enable it to compete with modern languages. 5) In the future, PHP needs to deal with new challenges such as containerization and microservices, but its flexibility and active community make it adaptable.

PHP's Impact: Web Development and Beyond PHP's Impact: Web Development and Beyond Apr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

See all articles