Detecting that log file has been deleted or truncated on POSIX systems?

后端 未结 5 1326
难免孤独
难免孤独 2021-01-13 22:11

Suppose a long-running process writes to a log file. Suppose that log file is kept open indefinitely. Suppose that a careless system administrator deletes that log file.

5条回答
  •  天命终不由人
    2021-01-13 22:41

    Suppose the careless system administrator kills the process. Do you really want to protect against the admin doing random things? I guess you're just looking for a way to start a new logfile from time to time, like using logrotate. There it is enough to provide a way to manually let the program reopen the logfile. The standard way to do this is to listen for the HUP-Signal in the program, and reopen the logfile if it arrives:

    #include 
    
    volatile int f_sighup;
    
    void sighup_handler() {
      f_sighup = 1;
    }
    
    void trap_sighup() {
      struct sigaction sa;
      int rv;
    
      memset(&sa, 0, sizeof(struct sigaction));
      sa.sa_handler = &sighup_handler;
      rv = sigaction(SIGHUP, &sa, NULL);
      if (-1 == rv) {
        fprintf(stderr, "warning: setting SIGHUP signal handler failed");
      }
    }
    
    int main() {
      f_sighup = 0;
      trap_sighup();
      ...
    }
    

    Then regularly check the f_sighup flag in the main program to see if the logfile should be reopened. This plays nice with tools like logrotate, which can rename the old logfile and then call kill -s HUP $PID. And the careless sysadmin can do this manually, after deleting (or better renaming) the old logfile.

提交回复
热议问题