Help! File Locking
Donn Cave
donn at u.washington.edu
Fri Jul 9 12:31:16 EDT 1999
More information about the Python-list mailing list
Fri Jul 9 12:31:16 EDT 1999
- Previous message (by thread): htmllib, cgi, HTMLfmt, genCGI, HTMLgen, html, Zope, ...
- Next message (by thread): Help! File Locking
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
chacs <cs at ctzen.com> writes: | 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() I'd guess there may be a hole in the file interlocks here. The file object "f" buffers writes (in the underlying C library stdio). The real I/O to the file doesn't happen until the close(), which happens after the file lock has been released and the other process waiting for the lock wakes up. Solution would be to insert f.flush() before releasing the lock. Or just use posix open/read/write functions directly. Donn Cave, University Computing Services, University of Washington donn at u.washington.edu ............................. | 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
- Previous message (by thread): htmllib, cgi, HTMLfmt, genCGI, HTMLgen, html, Zope, ...
- Next message (by thread): Help! File Locking
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
More information about the Python-list mailing list