Truncating a file while it's being used (Linux)

后端 未结 13 2166
名媛妹妹
名媛妹妹 2020-12-05 01:54

I have a process that\'s writing a lot of data to stdout, which I\'m redirecting to a log file. I\'d like to limit the size of the file by occasionally copying the current

13条回答
  •  星月不相逢
    2020-12-05 02:44

    @Hobo use freopen(), it reuses stream to either open the file specified by filename or to change its access mode. If a new filename is specified, the function first attempts to close any file already associated with stream (third parameter) and disassociates it. Then, independently of whether that stream was successfully closed or not, freopen opens the file specified by filename and associates it with the stream just as fopen would do using the specified mode.

    if a thirdparty binary is generating logs we need to write a wrapper which will rotate the logs, and thirdparty will run in proxyrun thread as below.

    #include 
    #include 
    #include 
    #include 
    #include 
    
    using namespace std;
    
    extern "C" void * proxyrun(void * pArg){
       static int lsiLineNum = 0;
       while(1) 
       {
         printf("\nLOGGER: %d",++lsiLineNum);
         fflush(stdout);
       }
      return NULL;
    }
    
    
    int main(int argc, char **argv)
    {
      pthread_t lThdId;
      if(0 != pthread_create(&lThdId, NULL, proxyrun, NULL))
      {
        return 1;
      }
    
      char lpcFileName[256] = {0,};
    
      static int x = 0;
    
      while(1)
      {
        printf("\n<<
    >>"); fflush(stdout); sprintf(lpcFileName, "/home/yogesh/C++TestPrograms/std.txt%d",++x); freopen(lpcFileName,"w",stdout); sleep(10); } return 0; }

提交回复
热议问题