fcntl.flock - how to implement a timeout?

前端 未结 4 648
离开以前
离开以前 2021-02-02 18:31

I am using python 2.7

I want to create a wrapper function around fcntl.flock() that will timeout after a set interval:

wrapper_function(timeout):
         


        
4条回答
  •  故里飘歌
    2021-02-02 18:59

    I'm a fan of shelling out to flock here, since attempting to do a blocking lock with a timeout requires changes to global state, which makes it harder to reason about your program, especially if threading is involved.

    You could fork off a subprocess and implement the alarm as above, or you could just exec http://man7.org/linux/man-pages/man1/flock.1.html

    import subprocess
    def flock_with_timeout(fd, timeout, shared=True):
        rc = subprocess.call(['flock', '--shared' if shared else '--exclusive', '--timeout', str(timeout), str(fd)])
        if rc != 0:
            raise Exception('Failed to take lock')
    

    If you have a new enough version of flock you can use -E to specify a different exit code for the command otherwise succeeding, but failed to take the lock after a timeout, so you can know whether the command failed for some other reason instead.

提交回复
热议问题