守护进程

编写一个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\n");
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\n");
41                exit(1);
42            }
43            sleep(10);
44            memset(buf,'\0',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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值