首先建立守护进程,在该守护进程中创建一个子进程,子进程暂停10秒,然后自动退出,并由守护进程收集子进程的退出信息,这些信息都在/var/log/messages中输出,子进程退出后,守护进程循环暂停,间隔为10秒。
#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>
#include <syslog.h>
#include <string.h>
#include <sys/wait.h>
#include <fcntl.h>
#define MAXFILE 65535
main()
{
pid_t pc,sid,pid;
int i,fd,len,status;
char buf[10];
pc=fork();
if(pc<0)
{
printf("error in fork!");
exit(1);
}
else if(pc>0) exit(0);
setsid();
chdir("/");
umask(0);
for(i=0;i<MAXFILE;i++)
close(i);
while(1){
if((fd=open("/tmp/dameon3.log",O_CREAT|O_WRONLY|O_APPEND,0600))<0)
{
perror("open");
exit(1);
}
pid=fork();
if(pid<0)
{
printf("error in fork!");
exit(1);
}
else if(pid==0)
{
sleep(10);
exit(0);
}
else
{
waitpid(pid,&status,0);
}
buf[0]=status/10000+'0';
buf[1]=status/1000+'0';
buf[2]=status/100+'0';
buf[3]=status/10+'0';
write(fd,buf,10);
close(fd);
sleep(10);
}
}