search
HomeBackend DevelopmentPHP TutorialPHP daemon process. Add the linux command nohup to execute the task once per second_PHP tutorial

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
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
PHP's Purpose: Building Dynamic WebsitesPHP's Purpose: Building Dynamic WebsitesApr 15, 2025 am 12:18 AM

PHP is used to build dynamic websites, and its core functions include: 1. Generate dynamic content and generate web pages in real time by connecting with the database; 2. Process user interaction and form submissions, verify inputs and respond to operations; 3. Manage sessions and user authentication to provide a personalized experience; 4. Optimize performance and follow best practices to improve website efficiency and security.

PHP: Handling Databases and Server-Side LogicPHP: Handling Databases and Server-Side LogicApr 15, 2025 am 12:15 AM

PHP uses MySQLi and PDO extensions to interact in database operations and server-side logic processing, and processes server-side logic through functions such as session management. 1) Use MySQLi or PDO to connect to the database and execute SQL queries. 2) Handle HTTP requests and user status through session management and other functions. 3) Use transactions to ensure the atomicity of database operations. 4) Prevent SQL injection, use exception handling and closing connections for debugging. 5) Optimize performance through indexing and cache, write highly readable code and perform error handling.

How do you prevent SQL Injection in PHP? (Prepared statements, PDO)How do you prevent SQL Injection in PHP? (Prepared statements, PDO)Apr 15, 2025 am 12:15 AM

Using preprocessing statements and PDO in PHP can effectively prevent SQL injection attacks. 1) Use PDO to connect to the database and set the error mode. 2) Create preprocessing statements through the prepare method and pass data using placeholders and execute methods. 3) Process query results and ensure the security and performance of the code.

PHP and Python: Code Examples and ComparisonPHP and Python: Code Examples and ComparisonApr 15, 2025 am 12:07 AM

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

PHP in Action: Real-World Examples and ApplicationsPHP in Action: Real-World Examples and ApplicationsApr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP: Creating Interactive Web Content with EasePHP: Creating Interactive Web Content with EaseApr 14, 2025 am 12:15 AM

PHP makes it easy to create interactive web content. 1) Dynamically generate content by embedding HTML and display it in real time based on user input or database data. 2) Process form submission and generate dynamic output to ensure that htmlspecialchars is used to prevent XSS. 3) Use MySQL to create a user registration system, and use password_hash and preprocessing statements to enhance security. Mastering these techniques will improve the efficiency of web development.

PHP and Python: Comparing Two Popular Programming LanguagesPHP and Python: Comparing Two Popular Programming LanguagesApr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

The Enduring Relevance of PHP: Is It Still Alive?The Enduring Relevance of PHP: Is It Still Alive?Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

See all articles

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software