2012-01-31 72 views
1

我有一個簡單的例子:如何使用鎖定文件的fcntl讀取狀態?

#!/usr/bin/python 
import time 
import fcntl 
file = open("e", "w") 
fcntl.lockf(file.fileno(),fcntl.LOCK_EX) 
file.write("foo") 
file.close() 

如何知道鎖定的文件或沒有? (不等待文件解鎖)

回答

3

這就是fcntl.LOCK_NB的用途。例如:

import warnings 
try: 
    fcntl.flock(myfile, fcntl.LOCK_EX|fcntl.LOCK_NB) 
except IOError: 
    warnings.warn("can't immediately write-lock the file ($!), blocking ...") 
    fcntl.flock(myfile, fcntl.LOCK_EX) 

file access