Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Example Analysis of Daemon process under linux

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

本篇内容主要讲解"linux下的守护进程实例分析",感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习"linux下的守护进程实例分析"吧!

shell控制的php常驻进程的例子

代码如下:

#!/bin/sh

#filename test.sh

#绝对定位该文件的位置,不随执行目录而变化

cd $(cd "$(dirname "$0")";pwd)

readonly path=$(pwd)/

file=$1;

runfile="${path}data/${file}.run"

diefile="${path}data/${file}.die"

readonly file="${path}${file}.php"

if [ ! -f "$file" ]; then

echo "please select a exists file"

elif [ ! -f "$runfile" ]; then

#这里进行判断如果runfile文件不存在,则表示该进程不存在,下面启动进程

echo $$>${runfile}

while true

do

if [ ! -f $diefile ]; then

#这里如果diefile文件不存在,则表示程序继续执行,否则进入else,执行退出操作

/usr/bin/php -f ${file}

touch $runfile

sleep 1

else

#如果diefile文件存在清除runfile和diefile退出

if rm -rf $runfile && rm -rf $diefile ; then

exit

fi

fi

done

else

#这里是在存在runfile的情况下试图启动该进程

oldpid=`cat $runfile`

newpid=`ps aux | grep "process.sh $1" | grep -v grep | grep "$oldpid" | awk '{print $2}'`

if [[ $oldpid -eq $newpid ]]; then

#如果runfile中的进程号和正在运行的目标进程号一致,表明一切安好^_^

echo "the process is runing now"

exit

else

#如果用runfile中的进程号匹配不到正在运行的目标进程,则表示进程有问题,直接删除runfile并结束运行的进程

echo "error situation,kill the run process and delete the run file"

ps aux | grep "process.sh $1" | grep -v 'grep' | awk '{print $2}' | grep -v $$ | xargs --no-run-if-empty kill

if [ $? -eq 0 ]; then

rm -f $runfile

else

echo $?>${path}/data/error

fi

fi

fi

只里面有几个要强调的地方:

我用这个shell去调用php程序,这个没有局限性,这里要说明的是这种运行常驻进程的方法

在runfile存在,但进程号对不上杀进程时(也就是红色额else所执行的地方),一定要 `grep -v $$`,作用是过滤掉当前运行的进程,要不然都被杀掉了,将后面的就不执行了

还有一个要注意的地方就是关于自动重启了

自动重启可以放在crontab中,每隔一段时间执行一次,具体情况具体对待。

复制代码 代码如下:

crontab -e

#打开当前用户日程表,添加模式

#日程表中有5个星号,f1,f2,f3,f4,f5,

#其中f1表示分,f2表示时,f3表示日,f4表示月,f5表示一个星期第几天

#*表示每分/时/日/月/周天,*/n表示每n分/时/......执行一次

*/2 * * * * /root/test.sh

#没2分钟执行一次

这样一个完整的常驻进程功能就完成了,想要终止进程是只需要在对应的目录下进行touch ${diefile}即可。

到此,相信大家对"linux下的守护进程实例分析"有了更深的了解,不妨来实际操作一番吧!这里是网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report