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

后端 未结 5 1319
难免孤独
难免孤独 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

    In response to søren-holm's answer

    When a file is closed the modification time is changed.

    that doesn't appear to be correct:

    import os
    from time import sleep
    
    TMPF = '/tmp/f'
    
    def print_stats():
        print("%s, %s" % (os.stat(TMPF).st_mtime, os.stat(TMPF).st_ctime))
        sleep(1.1)
    
    print("Opening...")
    with open(TMPF, 'w') as f:
        print_stats()
        print("Writing...")
        os.write(f.fileno(), 'apple')
        print_stats()
        print("Flushing...")
        f.flush()
        print_stats()
        print("Closing...")
    
    print_stats()
    

    Produces:

    Opening...
    1483052647.08, 1483052647.08
    Writing...
    1483052648.18, 1483052648.18
    Flushing...
    1483052648.18, 1483052648.18
    Closing...
    1483052648.18, 1483052648.18
    

    Admittedly, there's a bit of Python magic going on in there; that write() is not reasonably guaranteed to be flushed automatically, but the point stands that mtime is updated when the file is modified, not when the file is closed. The behavior of ctime is going to depend on your filesystem and its mount options.

提交回复
热议问题