zoukankan      html  css  js  c++  java
  • 守护进程

    编写一个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 }
  • 相关阅读:
    andorid UI事件 监听器
    12小时进制的时间输出的编辑代码
    Java运算符
    运算符的优先级
    UTF-8
    对ASCII的了解
    数组
    Java语法基础
    Java的跨平台
    指针的了解
  • 原文地址:https://www.cnblogs.com/codeyuan/p/4357856.html
Copyright © 2011-2022 走看看