2 flock.py -- Simple exclusive lock fcntl test program in Python.
4 Usage: python /path/to/lock_test.py
6 The script will try to open(create if needed), then lock a 'lock_test.txt'
7 file in the current working directory, write its PID in it, then wait for
8 the user to press enter, then release the lock, close the file and exit.
10 Tested on both stock Python 2.3.5 and Python 2.4.2
12 from sys
import stdout
, exc_info
13 from traceback
import print_exception
14 from os
import getcwd
, getpid
15 from os
.path
import join
16 from fcntl
import lockf
, LOCK_UN
, LOCK_EX
19 filename
= join(getcwd(),'lock_test.txt')
20 print 'Opening or creating "%s"...' % filename
,
21 f
= file(filename
,'a')
23 print 'Acquiring lock...',
27 print 'Writing pid (%d)...' % getpid(),
28 print >> f
, "PID:", getpid()
30 raw_input('[Press enter to exit]')
31 print 'Releasing lock...',
34 print 'Closing file...',
40 print_exception(*exc_info())