fcntl.flock - how to implement a timeout?

前端 未结 4 702
离开以前
离开以前 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:42

    Timeouts for system calls are done with signals. Most blocking system calls return with EINTR when a signal happens, so you can use alarm to implement timeouts.

    Here's a context manager that works with most system calls, causing IOError to be raised from a blocking system call if it takes too long.

    import signal, errno
    from contextlib import contextmanager
    import fcntl
    
    @contextmanager
    def timeout(seconds):
        def timeout_handler(signum, frame):
            pass
    
        original_handler = signal.signal(signal.SIGALRM, timeout_handler)
    
        try:
            signal.alarm(seconds)
            yield
        finally:
            signal.alarm(0)
            signal.signal(signal.SIGALRM, original_handler)
    
    with timeout(1):
        f = open("test.lck", "w")
        try:
            fcntl.flock(f.fileno(), fcntl.LOCK_EX)
        except IOError, e:
            if e.errno != errno.EINTR:
                raise e
            print "Lock timed out"
    

提交回复
热议问题