linux deamon

http://blog.csdn.net/u013485792/article/details/51507685

http://blog.csdn.net/hepeng597/article/details/9816751

 1 #include <unistd.h>
 2 #include <stdio.h>
 3 #include <stdlib.h>
 4 #include <time.h>
 5 #include <signal.h>
 6 #include <sys/param.h>
 7 #include <sys/types.h>
 8 #include <sys/stat.h>
 9 
10 void init_daemon(void)
11 {
12     int pid1, pid2;
13     int i;
14     pid1 = fork();
15     if( pid1 < 0 ){
16         fprintf( stderr, "fork failed, process exit
" );
17         exit(1);//fork失败,退出
18     }else if(pid1){
19         fprintf( stderr, "Child process created, pid = %d
", pid1 );
20         fprintf( stderr, "parent process exit
" );
21         exit(0);//是父进程,结束父进程
22     }
23 
24     //是第一子进程,后台继续执行
25     if(setsid() == -1){//第一子进程成为新的会话组长和进程组长
26         printf("setsid failed
");
27         exit(-1);
28     }
29 
30     //并与控制终端分离
31     pid2 = fork();
32     if( pid2 < 0 ){
33         fprintf( stderr, "fork failed, process exit
" );
34         exit(1);//fork失败,退出
35     }else if(pid2){
36         fprintf( stderr, "Child process created, pid = %d, " 
37             "create in %d
", pid2, pid1 );
38         fprintf( stderr, "process %d exit.
", pid1 );
39         exit(0);//是第一子进程,结束第一子进程
40     }
41 
42     //是第二子进程,继续
43     //第二子进程不再是会话组长
44     for(i=0;i< NOFILE;++i)//关闭打开的文件描述符
45         close(i);
46 
47     chdir("/tmp");//改变工作目录到/tmp
48     umask(0);
49     //umask(S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH);//重设文件创建掩码 mask = arg & 0777
50 
51     return;
52 }
53 
54 
55 int main()
56 {
57     FILE *fp;
58     time_t t;
59     init_daemon();//初始化为Daemon
60 
61     while(1){//每隔一分钟向test.log报告运行状态        
62         fp = fopen("test.log", "a");
63         if( fp >= 0 ){
64             t = time(NULL);
65             fprintf( fp, "I'm here at %s
", asctime(localtime(&t)) );
66             fclose(fp);
67         }
68 
69         sleep(60);//睡眠一分钟
70     }
71 
72     return 0;
73 }
原文地址:https://www.cnblogs.com/merlindu/p/6913332.html