多进程——守护进程例子

要求,创建守护进程,每隔两秒向文件daemon.txt中写入当前时间

 1 #include"my.h"
 2 #include<stdio.h>
 3 #include<time.h>
 4 #include<string.h>
 5 #include<fcntl.h>
 6 #include<sys/stat.h>
 7 
 8 int main(){
 9 
10     pid_t pid;
11     int i,fd;
12     //char *buf="this is daemon
";
13     char buf[128]={0};
14     time_t t;
15 
16     pid=fork();
17     if(pid<0){
18     
19         perror("fork error");
20         exit(1);
21     }
22     else if(pid>0){
23     
24         
25     //printf("#######################");
26         exit(0);
27     }
28     printf("#######################");
29     setsid();
30     chdir("/tmp");
31     umask(0);
32     for(i=0;i<getdtablesize();i++){
33     
34         close(i);
35     }
36     while(1){
37     
38         if((fd=open("daemon.txt",O_CREAT|O_WRONLY|O_TRUNC,0600))<0){
39         
40             perror("open file error
");
41             exit(1);
42         }
43 
44         time(&t);
45         sprintf(buf,"time=%s",ctime(&t));
46         write(fd,buf,strlen(buf));
47         close(fd);
48         sleep(3);
49     }
50     exit(0);
51 }

错误分析:

(1)缺少头文件sys/wait.h  导致umask()报错;

(2)创建daemon.txt是路径缺省,本来以为是在和daemon.c一个文件夹错误,是在第三部chdir()创建的工作目录/tmp下。

(3)printf("############"), 不会显示的原因,已经脱离当前中断所以不会显示

原文地址:https://www.cnblogs.com/lanbofei/p/9575410.html