Advertisement
Guest User

Untitled

a guest
Jan 23rd, 2017
104
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.70 KB | None | 0 0
  1. #! /usr/bin/env python
  2.  
  3. import errno
  4. import fcntl
  5. import sys
  6.  
  7. FILE = './LOCK_ME.txt'
  8.  
  9. print 'Python lockf()!'
  10.  
  11. # Open a file
  12. print 'Opening file {}'.format(FILE)
  13. f = open(FILE, 'a+', 0)
  14.  
  15. # Lock fun
  16. print 'Acquring lock on {}...'.format(FILE)
  17. try:
  18. # LOCK_EX to acquire an exclusive lock, no one else gets in
  19. # LOCK_NB to not block but raise exception if already locked
  20. fcntl.lockf(f, fcntl.LOCK_EX | fcntl.LOCK_NB)
  21. except IOError as e:
  22. if e.errno not in (errno.EACCES, errno.EAGAIN):
  23. raise
  24. else:
  25. print 'Already locked!'
  26. sys.exit(1)
  27.  
  28. print 'Locked {}'.format(FILE)
  29. _ = raw_input('Press enter to unlock and exit...')
  30. fcntl.lockf(f, fcntl.LOCK_UN)
  31. f.close()
  32. print 'So long!'
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement