Help! File Locking

chacs cs at ctzen.com
Fri Jul 9 11:18:37 EDT 1999


Hi All,

Need some help in file locking.

x1.py:
  import fcntl, FCNTL
  f = open('myfile', 'r+')
  fcntl.flock(f.fileno(), FCNTL.LOCK_EX)
  input()
  x = str(int(f.readline()) + 1)
  f.seek(0)
  f.write(x)
  fcntl.flock(f.fileno(), FCNTL.LOCK_UN)
  f.close()

x2.py:
  import fcntl, FCNTL
  f = open('myfile', 'r+')
  fcntl.flock(f.fileno(), FCNTL.LOCK_EX)
  x = str(int(f.readline()) + 1)
  f.seek(0)
  f.write(x)
  fcntl.flock(f.fileno(), FCNTL.LOCK_UN)
  f.close()

Both script are the same except x1 has an additional input() statement.

Basically, what the script does is to open a file, lock it and update
the first line to the next higher number.

My problem is (assume file content is "0"):

1. in shell 1, run x1.py, x1 got lock and block at input().
2. in shell 2, run x2.py, x2 block at flock().
3. in shell 1, input something to unblock input().
4. x1 update "0" to "1", unlock and exit.
5. x2 gets lock, BUT instead of getting the new file content (i.e. "1")
written by x1, it got the old content and update the file to "1" again
(instead of reading "1" and update to "2").

Any idea what is wrong ?

Thanx in advance.

C S Chang
cs at ctzen.com


Sent via Deja.com http://www.deja.com/
Share what you know. Learn what you don't.




More information about the Python-list mailing list