Home php教程 php手册 php守护进程 加linux命令nohup实现任务每秒执行一次

php守护进程 加linux命令nohup实现任务每秒执行一次

Jun 06, 2016 pm 08:38 PM
nohup daemon

那么有了这个命令以后我们php就写成shell 脚本使用循环来让我们脚本一直运行下去,不管我们终端窗口是否关闭都能够让我们php 脚本一直运行下去。

Unix中 nohup 命令功能就是不挂断地运行命令,同时 nohup 把程序的所有输出到放到当前目录 nohup.out 文件中,如果文件不可写,则放到 /nohup.out 文件中。那么有了这个命令以后我们php就写成shell 脚本使用循环来让我们脚本一直运行下去,不管我们终端窗口是否关闭都能够让我们php 脚本一直运行下去。
马上动手写个 PHP 小程序,功能为每30秒记录时间,写入到文件
代码如下:
# 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);
}
?>

保存退出,然后赋予 for_ever.php 文件可执行权限:
# chmod +x for_ever.php
让它在再后台执行:
# nohup /home/andy/for_ever.php.php &
记得最后加上 & 符号,这样才能够跑到后台去运行
执行上述命令后出现如下提示:
[1] 5157
nohup: appending output to 'nohup.out'
所有命令执行输出信息都会放到 nohup.out 文件中
这时你可以打开 for_ever.php 同目录下的 for_ever.txt 和 nohup.out 看看效果!
好了,它会永远运行下去了,怎么结束它呢?
# 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
找到进程号 5157 杀之,你将看到
[1]+ Killed nohup /home/andy/for_ever.php
OK!
====================
在很多项目中,或许有很多类似的后端脚本需要通过crontab定时执行。比如每10秒检查一下用户状态。脚本如下:
@file: /php_scripts/scan_userstatus.php
代码如下:
#!/usr/bin/env php -q
$status = has_goaway();
if ($status) {
//done
}
?>

通过crontab定时执行脚本scan_userstatus.php
#echo “*:*/10 * * * * /php_scripts/scan_userstatus.php”
这样,每隔10秒钟,就会执行该脚本。
我们发现,在短时间内,该脚本的内存资源还没有释放完,又启用了新的脚本。也就是说:新脚本启动了,旧脚本占用的资源还没有如愿释放。如此,日积月累,浪费了很多内存资源。我们对这个脚本进行了一下改进,改进后如下:
@file: /php_scripts/scan_userstatus.php
代码如下:
#/usr/bin/env php -q
while (1) {
$status = has_goaway();
if ($status) {
//done
}
usleep(10000000);
}
?>

这样,不需要crontab了。可以通过以下命令执行脚本,达到相同的功能效果
#chmod +x /php_scripts/scan_userstatus.php
#nohup /php_scripts/scan_userstatus.php &
在这里,我们通过&将脚本放到后台运行,为了防止随着终端会话窗口关闭进程被杀,我们使用了nohup命令。那么有没有办法,不使nohup命令,也能够运行呢,就像Unin/Linux Daemon一样。接下来,就是我们要讲的守护进程函数。
什么是守护进程?一个守护进程通常补认为是一个不对终端进行控制的后台任务。它有三个很显著的特征:在后台运行,与启动他的进程脱离,无须控制终端。常用的实现方式是fork() -> setsid() -> fork() 详细如下:
@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);
}
}
?>

实现了守护进程函数以后,则可以建立一个常驻进程,所以只需要执行一次:
#/php_scripts/scan_userstatus.php
这里较为关键的二个php函数是pcntl_fork()和posix_setsid()。fork()一个进程,则表示创建了一个运行进程的副本,副本被认为是子进程,而原始进程被认为是父进程。当fork()运行之后,则可以脱离启动他的进程与终端控制等,也意味着父进程可以自由退出。 pcntl_fork()返回值,-1表示执行失败,0表示在子进程中,而返进程ID号,则表示在父进程中。在这里,退出父进程。setsid(),它首先使新进程成为一个新会话的“领导者”,最后使该进程不再控制终端,这也是成为守护进程最关键的一步,这意味着,不会随着终端关闭而强制退出进程。对于一个不会被中断的常驻进程来说,这是很关键的一步。进行最后一次fork(),这一步不是必须的,但通常都这么做,它最大的意义是防止获得控制终端。(在直接打开一个终端设备,而且没有使用O_NOCTTY标志的情况下, 会获得控制终端).
其它事项说明:
1) chdir() 将守护进程放到总是存在的目录中,另外一个好处是,你的常驻进程不会限制你umount一个文件系统。
2)umask() 设置文件模式,创建掩码到最大的允许限度。如果一个守护进程需要创建具有可读,可写权限的文件,一个被继承的具有更严格权限的掩码会有反作用。
3)fclose(STDIN), fclose(STDOUT), fclose(STDERR) 关闭标准I/O流。注意,如果有输出(echo),则守护进程会失败。所以通常将STDIN, STDOUT, STDERR重定向某个指定文件.
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

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)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 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)

Analysis of the function and principle of nohup Analysis of the function and principle of nohup Mar 25, 2024 pm 03:24 PM

Analysis of the role and principle of nohup In Unix and Unix-like operating systems, nohup is a commonly used command that is used to run commands in the background. Even if the user exits the current session or closes the terminal window, the command can still continue to be executed. In this article, we will analyze the function and principle of the nohup command in detail. 1. The role of nohup: Running commands in the background: Through the nohup command, we can let long-running commands continue to execute in the background without being affected by the user exiting the terminal session. This needs to be run

How to shut down after running nohup command How to shut down after running nohup command Mar 18, 2024 pm 03:00 PM

Four methods: Find the process ID (PID) and kill the process using the "kill" command; kill all "nohup" processes using the "killall" command (use with caution); check the "nohup.out" file for relevant information. Through these methods, users can effectively shut down the tasks executed in the background by the "nohup" command.

Python server programming: how daemons are implemented Python server programming: how daemons are implemented Jun 18, 2023 pm 08:04 PM

Python is a very popular programming language, especially widely used in network programming. Server-side programming is also one of them. In server-side programming, daemon processes are a common concept. This article introduces how to implement daemon processes in Python server programming. What is a daemon process? When the server-side program is running, in order to ensure the long-term stable operation of the program, we need to convert it into a daemon process. A daemon is a process that runs continuously in the background and does not occupy a console or login

Use nohup and & to improve process control efficiency Use nohup and & to improve process control efficiency Mar 25, 2024 pm 04:15 PM

In recent years, with the continuous development of information technology, most work cannot be done without the help of computers. During computer operation, we often encounter situations where multiple processes need to be run at the same time, and improving process control efficiency is very critical. This article will introduce how to use the nohup and & commands in Linux systems to improve process control efficiency. 1. Understand the nohup and & commands. In Linux systems, nohup is a command used to ignore the hang signal. It can make the command run in the background, even if the user exits the terminal.

What does nohup mean? What does nohup mean? Mar 18, 2024 pm 03:14 PM

The nohup command is a tool used in Unix/Linux systems to execute commands in the background. Its function is to make the command ignore the hang-up signal and the execution will not be interrupted even if the terminal is closed. Usually, nohup will redirect the command output to the nohup.out file for subsequent viewing.

The difference between nohup and & The difference between nohup and & Mar 18, 2024 pm 02:48 PM

In Unix/Linux systems, nohup and && are both methods used to run commands or programs in the background. nohup is more suitable for long-running tasks because it is not affected by terminal status, can continue to execute, and can manage output. And && is suitable for short-lived background tasks, used when the results need to be checked later.

Detailed explanation of nohup command Detailed explanation of nohup command Oct 25, 2023 pm 04:20 PM

nohup is a commonly used command in Unix and Unix-like systems. It is used to run commands in the background and redirect the output of the command to a file to keep running even after the user logs out or the terminal is closed. Detailed explanation and usage of the nohup command: "nohup command [parameters] [input file] [output file]", where the command is the command to be run in the background, the parameters are the options and parameters of the command, and the input file is the input file of the command , the output file is the output file of the command.

How to correctly use nohup for background task processing How to correctly use nohup for background task processing Mar 26, 2024 am 09:39 AM

How to correctly use nohup for background task processing In daily work, we often need to perform some time-consuming tasks, such as file copying, data processing, etc. In order not to affect our work efficiency and ensure that tasks can run stably in the background, we can use the nohup command to start these tasks. This article will introduce how to correctly use nohup for background task processing. What is nohup command? nohup is a command in Unix and Unix-like operating systems that is used to run commands or scripts in the background.

See all articles