flock() question
Steve Purcell
stephen_purcell at yahoo.com
Tue Feb 6 05:44:36 EST 2001
Carsten Gaebler wrote:
> It seems I don't understand file locking. In the following example the
> parent process locks a file and then the child process locks the same file
> but does not wait until the parent unlocks it. What am I doing wrong?
>From the 'flock' man page:
"A file is locked (i.e., the inode), not the file descriptor."
So the correct procedure is to open the lock file separately in each process:
pid = os.fork()
if pid == 0:
f = open("/tmp/locktest", "w")
time.sleep(1)
print "Child: locking file"
fcntl.flock(f.fileno(), FCNTL.LOCK_EX)
print "Child: file locked"
time.sleep(5)
os._exit(0)
else:
f = open("/tmp/locktest", "w")
print "Parent: locking file"
fcntl.flock(f.fileno(), FCNTL.LOCK_EX)
print "Parent: file locked"
time.sleep(10)
fcntl.flock(f.fileno(), FCNTL.LOCK_UN)
--
Steve Purcell, Pythangelist
Get testing at http://pyunit.sourceforge.net/
Available for consulting and training.
"Even snakes are afraid of snakes." -- Steven Wright
More information about the Python-list
mailing list