Home  >  Article  >  php教程  >  PHP 做守护进程

PHP 做守护进程

WBOY
WBOYOriginal
2016-06-06 19:54:131257browse

http://www.21andy.com/blog/20100228/1728.html Unix中 nohup 命令功能就是不挂断地运行命令,同时 nohup 把程序的所有输出到放到当前目录 nohup.out 文件中,如果文件不可写,则放到 用户主目录/nohup.out 文件中。那么有了这个命令以后我们php就写成shell

http://www.21andy.com/blog/20100228/1728.html


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 杀之,你将看到


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