Python3 os.open与fcntl.LOCK_EX无法正常工作

时间:2017-03-30 15:42:06

标签: locking python-3.4

似乎os.open()无法正常使用fcntl.LOCK_EX。我重现它的测试代码是:

#!/usr/bin/python3.4

import fcntl, os, signal, time

os.fork()

class TimeoutException(Exception): pass

def signal_handler(signum, frame):
    raise TimeoutException()

while True:
    try:
        signal.signal(signal.SIGALRM, signal_handler)
        signal.alarm(5)
        f = os.open("python3.4-flock-test", os.O_RDWR|os.O_CREAT)
        fcntl.flock(f, fcntl.LOCK_EX)
        print(os.getpid(), "write to file")
        os.write(f, bytes("test", "utf-8"))
        time.sleep(1)
        fcntl.flock(f, fcntl.LOCK_UN)
        os.close(f)
        signal.alarm(0)
    except TimeoutException:
        print(os.getpid(), "flock runs on a timeout")

输出如下:

# ./flock-test
21819 write to file
21819 write to file
21819 write to file
21819 write to file
21819 write to file
21818 flock runs on a timeout
21819 write to file
21819 write to file

有没有人解释为什么以下代码剪断不起作用?

1 个答案:

答案 0 :(得分:0)

'os.open'在该示例中完美地运行,但是不需要os.O_RDWR,而是需要O_WRONLY。