


PHP 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
Write a PHP applet immediately. The function is to record time every 30 seconds and write it to a file
# 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
#!/ 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
#/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
#/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.

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python are both high-level programming languages that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

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 originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

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 remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

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

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values and handle functions that may return null values.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

Dreamweaver Mac version
Visual web development tools

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

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