您的位置:首页 > 其它

创建守护进程:先建立守护进程,在守护进程建立一个子进程,该子进程暂停10s,然后退出,并由该守护进程收集子进程退出的消息。子进程,守护进程的退出消息都在/var/log/message中输出,子进程退

2016-08-09 20:50 429 查看
#include <stdio.h>

#include <stdlib.h>

#include <sys/types.h>

#include <sys/stat.h>

#include <unistd.h>

#include <sys/wait.h>

#include <string.h>

#include <fcntl.h>

#define MAXFILE 65535

int main(void)

{
pid_t child1,child2;
int i,len,fd;

char *buf="This is a dameon";
len=strlen(buf);

 
child1=fork();
if(child1==-1)
{
printf("child1 fork\n");
exit(1);
}
else if(child1>0)
exit(0);
//openlog("exc2_info",LOG_PID,LOG_DAEMON);
setsid();
chdir("/");
umask(0);
for(i=0;i<MAXFILE;i++)
{
close(i);

     }

     

   if((fd=open("/var/log/message", O_CREAT|O_WRONLY|O_APPEND, 0600)) < 0)
{
printf("open file error.\n");
exit(1);
}

     
child2=fork();
if(child2==-1)
{
printf("child2 fork\n");
exit(1);
}
else if(child2==0)
{
//printf("cchild2 will sleep for 10s\n");
sleep(10);
write(fd, buf, len+1);
exit(0);
}
else
{
waitpid(child2,NULL,0);
//printf("child1 noticed that child2 has exited\n");
while(1)
{
sleep(10);
write(fd, buf, len+1);
}
close(fd);
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐