- 论坛徽章:
- 0
|
谢谢各位对我的问题的关注和支持.现在把我的想法说一下,请大家指教.
先说一下我的需求:
我写了一个守护进程,每隔一个间隔时间(参数化)读取固定文件夹下的文件,然后做相应的处理.该进程是由startup.sh来启动的.另外停止进程是由stop.sh来完成的.
需求要求在停止进程的时候判定读取一个文件后相应的处理有没有完成.如果没有完成,需要等到它完成后再停止.
2楼的sleetboy建议用killall 进程名字,4楼的gawk建议用popen把ps -ef|grep xxx的东西读出来处理.这两种方法因为无法实现守护进程和停止进程之间的联系,
可能有一定的困难.7楼的happy_fish100建议通过sigaction或signal捕获SIGINT或SIGTERM信号.我觉得比较好.只是小弟昨天试了一下,好象没有成功.我不知道
是不是和守护进程有关.现在将代码贴上来,大家给提提建议.谢谢.
守护进程主程序aa.c:
void quit(int signo)
{
char strProcessID[128];
memset(strProcessID, 0, sizeof(strProcessID));
char strCmd[128];
memset(strCmd, 0, sizeof(strCmd));
sprintf(strCmd, "ps -e|grep aa|cut -c 1-8");
FILE * fp = NULL;
fp = popen(strCmd, "r");
while(fgets(strProcessID, sizeof(strProcessID), fp))
{
printf("strProcessID=%s\n", strProcessID);
memset(strCmd, 0, sizeof(strCmd));
sprintf(strCmd, "kill -s USR1 %s", strProcessID);
if (0 > system(strCmd))
{
WriteLog("无法终止aa系统\n");
return -1;
}
}
pclose(fp);
return 0;
}
main()
{
signal(SIGTTOU, SIG_IGN);
signal(SIGTTIN, SIG_IGN);
signal(SIGTSTP, SIG_IGN);
signal(SIGHUP, SIG_IGN);
struct sigaction act;
act.sa_handler = quit;
act.sa_flags = 0;
sigemptyset(&act.sa_mask);
sigaction(SIGTERM, &act, NULL);
if (0 != fork())
{
exit(1);
}
if (0 > setsid())
{
exit(1);
}
if (0 != fork())
{
exit(1);
}
if (-1 == chdir("/tmp"))
{
exit(1);
}
umask(0);
signal(SIGCHLD, SIG_IGN);
while(1)
{
if (ERR_FILE_NOT_EXIST == aa_main()) /*文件夹下没有文件,sleep10秒*/
{
sleep(10);
}
}
}
startup.sh:
#!/bin/sh
tmpfile=/tmp/aaProcessID
ps -e|grep aa|cut -c 1-8 > $tmpfile
chmod 775 $tmpfile
cnt=`wc -l $tmpfile | cut -c 1-8`
if [ $cnt -gt 0 ]
then
for i in `cat $tmpfile`
do
kill -s USR1 $i
done
fi
test -f $tmpfile
if [ $? -eq 0 ]
then
rm -f $tmpfile
fi
./aa
stop.sh:
#!/bin/sh
tmpfile=/tmp/aaProcessID
ps -e|grep aa|cut -c 1-8 > $tmpfile
chmod 775 $tmpfile
cnt=`wc -l $tmpfile | cut -c 1-8`
if [ $cnt -gt 0 ]
then
for i in `cat $tmpfile`
do
kill -s USR1 $i
done
fi
test -f $tmpfile
if [ $? -eq 0 ]
then
rm -f $tmpfile
fi |
|