shell腳本 (文件名:my_exec.sh)php
############# 配置項 ###############################shell
keyword='a.php' #查找進程是否存在的關鍵詞
line=`ps aux | grep ${keyword} | wc -l` # 查看進程是否存在的命令
commend='php a.php' # nohup 執行的commend; 不要帶 輸出重定向 和 & !!!!!!
output_file='1.txt' #輸出重定向文件
pid_file='exec_pid.pid' #pid文件 確保惟一且文件夾可寫rest
############ 配置項 end ############################進程
###檢查狀態
function check_running(){
if [[ $line -lt 2 ]] ## 去除 gerp 時產生的進程
then
echo "未運行" ##### 未執行的操做
else
echo "正在運行" ##### 已執行的操做
fi
}io
function start_running(){function
if [[ $line -lt 2 ]]
then
echo "正在開始。。。。"
eval "nohup ${commend} >>${output_file} 2>&1 &"
echo $! > ${pid_file} #### 保存pid 文件
sleep 2
echo "成功"
else
echo "程序已經運行,請不要重複運行"後臺
fi
}配置
function stop_running(){
if [[ $line -lt 2 ]]
then
echo "程序未運行"
elif [ ! -f "$pid_file" ]
then
echo "pid文件不存在,請使用 kill 刪除進程"
else
echo "正在中止。。。。"
kill -9 `cat ${pid_file}` ##### 本身的中止方法 儘可能不要用 kill -9
rm -f $pid_file
sleep 2
echo "成功"
fidate
}
case $1 in
start):
start_running;
;;
check):
check_running;
;;
stop):
stop_running;
;;
restart):
stop_running;
start_running;
;;
*):
echo "請輸入命令: sh start_exec.sh【start|stop|restart|check】"file
;;
esac
php腳本 (本身的後臺腳本,必定要是可以長久運行的)
<?php
while(true){
sleep(1);
file_put_contents('1.txt',date('Y-m-d H:i:s')."\r\n",FILE_APPEND);
}
?>
方法 sh shart_exec.sh (start | stop | restart | check)