fcntl.flock - how to implement a timeout?

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

    For Python 3.5+, Glenn Maynard's solution no longer works because of PEP-475. This is a modified version:

    import signal, errno
    from contextlib import contextmanager
    import fcntl
    
    @contextmanager
    def timeout(seconds):
        def timeout_handler(signum, frame):
            # Now that flock retries automatically when interrupted, we need
            # an exception to stop it
            # This exception will propagate on the main thread, make sure you're calling flock there
            raise InterruptedError
    
        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 InterruptedError:
            # Catch the exception raised by the handler
            # If we weren't raising an exception, flock would automatically retry on signals
            print("Lock timed out")
    

提交回复
热议问题