linux守护进程小例
时间:2010-09-05 来源:楚夕
此处我借用fork()函数创建三个并发的守护进程,借用syslog调试程序运行
其中,第二子进程child2作为gedit工具调用的监控守护进程,第一子进程child1借助syslog日志监控守护进程的运行,第二子进程child3此处用来检查是否有新邮件收到,收到则将邮件内容输出到重定向输出文件
标记:一般来说守护进程无法在终端中调试,也无法在终端输出,故而均采用syslog()函数进行跟踪调试
/*文件名为2.c*/
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <unistd.h>
#include <syslog.h>
#include <signal.h>
#include <sys/param.h>
#include <time.h>
#include <dirent.h>
int main()
{
pid_t child1,child2,child3;
struct stat buf;
int i,check=0,j=0;
time_t t;
DIR * dir;
struct dirent * ptr;
child1=fork();
if (child1>0)
exit(0);
else if(child1<0)
{
perror("创建子进程失败");
exit(1);
}
setsid();
chdir("/");
umask(0);
for(i=0;i<NOFILE;++i)
close(i);
openlog("守护进程程序信息",LOG_PID,LOG_DAEMON);
child2=fork();
if (child2==-1)
{
perror("创建子进程失败");
exit(2);
}
else if (child2==0)
{
i=0;
while(i++<100){
system("ps -ef|grep gedit> /home/king/gedit.log");
stat("home/king/gedit.log",&buf);
if (buf.st_size>180 && check==0)
{
t=time(0);
syslog(LOG_INFO,"gedit开始时间为: %s\n",asctime(localtime(&t)));
check=1;
}
if (buf.st_size<180 && buf.st_size>0 && check==1)
{
t=time(0);
syslog(LOG_INFO,"gedit结束时间为: %s\n",asctime(localtime(&t)));
check=0;
}
sleep(1);
}
}
else
{
child3=fork();
if (child3<0){
perror("创建子程序失败");
exit(3);
}
else if (child3==0){
j=0;
dir=opendir("/var/spool/mail/king");
while (j<6){
j++;
sleep(10);
if ((ptr=readdir(dir))!=NULL){
system("cat /var/spool/mail/king/* > /home/king/mail.log");
}
}
closedir(dir);
}
else
{
t=time(0);
syslog(LOG_INFO,"守护进程开始时间为: %s\n",asctime(localtime(&t)));
waitpid(child2,NULL,0);
waitpid(child3,NULL,0);
t=time(0);
syslog(LOG_INFO,"守护进程结束时间为: %s\n",asctime(localtime(&t)));
closelog();
while (1)
sleep(10);
}
}
}
在下linux系统为ubuntu,主文件名为king
先在 var/spool/mail/king/下建一文本文件,便于测试第二子进程child3功能
在终端1中运行
sudo ./2
tail -f /var/log/syslog
监控程序运行
Sep 5 18:27:54 ubuntu 守护进程程序信息[26748]: 守护进程开始时间为: Sun Sep 5 18:27:54 2010#012
Sep 5 18:28:10 ubuntu 守护进程程序信息[26749]: gedit开始时间为: Sun Sep 5 18:28:10 2010#012
Sep 5 18:28:32 ubuntu 守护进程程序信息[26749]: gedit结束时间为: Sun Sep 5 18:28:32 2010#012
Sep 5 18:29:12 ubuntu 守护进程程序信息[26748]: 守护进程结束时间为: Sun Sep 5 18:29:12 2010#012
在终端2中运行
ps -ef | grep ./2
可观察到相应的守护进程运行
运行一个gedit文件,等待数秒后关闭
再等候一会到对应的守护进程全部停止关闭
最终在主目录下的mail.log中可看到邮件内容