The role of the resident process under Linux can not be ignored, but the problem can not be ignored, how to start the process, how to end the process, how to restart the process after the process is designed to be reasonable. Let's look at a shell-controlled example of a PHP resident process.
No nonsense, direct fishing dry, on the code, through the code to explain more easily understand:
#!/bin/SH
#filename test.sh #绝对定位该文件的位置, does not vary with the execution directory CD $ (CD"$ (dirname"$0")";pwd)readonly Path=$(pwd)/file=$1; Runfile="${path}data/${file}.run"Diefile="${path}data/${file}.die"ReadOnlyfile="${path}${file}.php"if[!-F"$file"]; Then Echo "Please select a exists file"elif[!-F"$RunFile"]; Then
#这里进行判断如果RunFile文件不存在, the process does not exist and the process starts
echo $$>${runfile} whiletrue if Then
#这里如果DieFile文件不存在, which means the program continues to execute, otherwise goes to else, performs an exit operation
/usr/bin/php-f ${" touch $RunFile sleep else
#如果DieFile文件存在清除RunFile和DieFile退出 if rm -rf $DieFile; then exit fi fi done else #这里是在存在RunFile的情况下试图启动该进程
oldpid = ' cat $RunFile ' Newpid = '
#如果RunFile中的进程号和正在运行的目标进程号一致 to show that everything is OK ^_^ Echo " The process is runing now " exit Else
#如果用RunFile中的进程号匹配不到正在运行的目标进程, it indicates a problem with the process, deleting the runfile directly and ending the running process Echo "Error Situation,kill The run process and delete the run file" PSAux |grep "process.sh $"|grep-V'grep'|awk '{print $}'|grep-V $$ |Xargs--no-run-if-emptyKill if[$?-eq0]; Then RM-F $RunFileElse Echo$?>${path}/data/Errorfi fifi
There are only a few places to emphasize:
- I use this shell to invoke the PHP program, this has no limitations, here is to explain this method of running the resident process
- The runfile exists, but the process number is not on the killing process (that is, where the red amount else executes), it must be 'grep -v $$ ', the role is to filter out the current running process, or else are killed, will not execute the back
- One more thing to watch out for is the automatic restart.
Automatic restart can be placed in the crontab, once every time, the specific situation of concrete treatment.
Crontab-e# Open the current user schedule, add mode # There are 5 asterisks in the timeline, F1,f2,f3,f4,f5,
#其中f1表示分, F2, F3 represents the day, F4 represents the month, F5 represents one weeks the first day
#* indicates every minute/hour/day/month/Sunday, */n means every n/hour/... Execute once */2 * * * * */root/test. SH #没2分钟执行一次
Such a complete resident process function is completed, and the need to terminate the process is only required in the corresponding directory to Touch ${diefile}.
The daemon under Linux