守护进程删除smarty的缓存文件(注释版) 博客分类: 程序 FPPHPBBSCC++
程序员文章站
2024-03-08 14:02:40
...
原文: 鸭嘴的Blog
偶参阅了网上资料加了注释.
<?php define("PID_PATH", "/tmp/delSmartyCache.pid"); global $argv; $cmd = $argv[1]; switch($cmd) { case 'start' : do_work(); break; case 'stop' : do_stop(); break; case 'status' : show_status(); break; default : show_usage(); break; } function do_work() { // 创建子进程(守护进程) $newid = pcntl_fork(); if ($newid == -1) { echo "pcntl_fork error\n"; exit; } if ($newid) { // 返回值大于0, 表示创建成功, 提示信息并结束父进程 echo "process delSmartyCache start successfully\n"; exit; } else { // 返回值为0, 表示父进程结束后进入子进程的运行阶段 // 取当前进程(子进程)的PID, 并写至进程文件 $pid = posix_getpid(); $fp = fopen(PID_PATH, "w"); fwrite($fp, $pid); fclose($fp); while (true) { $cmd = "rm -rf /elink/bbs_data/smarty/tmpl_c/*"; $re = popen("$cmd", "r"); // 打开一个指向删除进程的管道 $ret = fread($re, 1024); if ($ret != "") { // 将执行情况写入日志 $fp = fopen("/home/dexin/run_delSmartyCache.log","a+"); fwrite($fp, $ret); fclose($fp); } // 延时6秒 sleep(6); } } } // 停止守护进程 function do_stop() { if (file_exists(PID_PATH)) { // 读取守护进程PID $fp = fopen(PID_PATH, "r"); $pid = fread($fp, 10); // 退出守护进程 $ret = posix_kill($pid, SIGQUIT); if ($ret === true) { echo "process delSmartyCache stopped successfully\n"; } else { echo "fail stop process delSmartyCache\n"; } } else { echo "process delSmartyCache not found\n"; } } // 使用说明 function show_usage() { print <<<EOF Usage: php delSmartyCache.php <option> Options: start - Start the daemon stop - Stop daemon status - show the delSmartyCache daemon help - Show help EOF; } // 显示状态 function show_status() { if (file_exists(PID_PATH)) { $fp = fopen(PID_PATH, 'r'); $pid = fread($fp, 10); $ret = posix_kill($pid, 0); // 发送信号判断进程是否存活 if($ret === true) { echo "process delSmartyCache is alive\n"; exit; } else { echo "process delSmartyCache is down\nplease start the process\n"; exit; } } else { echo "pid file not exists\n"; exit; } }