How do I watch a file for changes?

前端 未结 25 2655
孤街浪徒
孤街浪徒 2020-11-21 07:13

I have a log file being written by another process which I want to watch for changes. Each time a change occurs I\'d like to read the new data in to do some processing on it

25条回答
  •  南笙
    南笙 (楼主)
    2020-11-21 07:52

    It should not work on windows (maybe with cygwin ?), but for unix user, you should use the "fcntl" system call. Here is an example in Python. It's mostly the same code if you need to write it in C (same function names)

    import time
    import fcntl
    import os
    import signal
    
    FNAME = "/HOME/TOTO/FILETOWATCH"
    
    def handler(signum, frame):
        print "File %s modified" % (FNAME,)
    
    signal.signal(signal.SIGIO, handler)
    fd = os.open(FNAME,  os.O_RDONLY)
    fcntl.fcntl(fd, fcntl.F_SETSIG, 0)
    fcntl.fcntl(fd, fcntl.F_NOTIFY,
                fcntl.DN_MODIFY | fcntl.DN_CREATE | fcntl.DN_MULTISHOT)
    
    while True:
        time.sleep(10000)
    

提交回复
热议问题