守护进程

编写一个linux下的进程守护程序,每隔十秒性日志文件中输出系统当前时间;

 1 #include<stdio.h>
 2 #include<stdlib.h>
 3 #include<string.h>
 4 #include<fcntl.h>
 5 #include<sys/types.h>
 6 #include<unistd.h>
 7 #include<sys/wait.h>
 8 #include<sys/stat.h>
 9 #include<time.h>
10 using namespace std;
11 
12 int main()
13 {
14         pid_t pid;
15         time_t now;
16         struct tm *timenow;
17         int i, fd;
18         char buf[1000];
19         pid = fork();
20         if (pid < 0)
21      {
22          printf("Error fork
");
23         exit(1);
24         }
25         else if (pid > 0)
26         {
27         exit(0);
28         }
29         setsid(); 
30         chdir("/"); 
31         umask(0); 
32         for(i = 0; i < getdtablesize(); i++) /* 第五步 */
33         {
34             close(i);
35         }
36         while(1)
37         {
38         if ((fd = open("/tmp/daemon1.log", O_CREAT|O_WRONLY|O_APPEND, 0600)) < 0)
39          {
40                printf("Open file error
");
41                exit(1);
42            }
43            sleep(10);
44            memset(buf,'',sizeof(buf));
45            time(&now);
46            timenow=localtime(&now);
47            strcpy(buf,asctime(timenow));
48            write(fd, buf, strlen(buf)+1 );
49             close(fd);
50             }
51            exit(0);
52 }
原文地址:https://www.cnblogs.com/codeyuan/p/4357856.html