| 37 | atexit.register(self.cleanup) |
| 38 | |
| 39 | def lock(self): |
| 40 | if self.lockPid is None: |
| 41 | self.lockPid = os.getpid() |
| 42 | if sys.platform == 'win32': |
| 43 | try: |
| 44 | # file already exists, we try to remove (in case previous execution was interrupted) |
| 45 | if os.path.exists(self.lockfile): |
| 46 | os.unlink(self.lockfile) |
| 47 | self.fd = os.open(self.lockfile, os.O_CREAT | os.O_EXCL | os.O_RDWR | os.O_TRUNC) |
| 48 | except OSError: |
| 49 | type, e, tb = sys.exc_info() |
| 50 | if e.errno == 13: |
| 51 | print 'Another instance of this application is already running' |
| 52 | sys.exit(-1) |
| 53 | print(e.errno) |
| 54 | raise |
| 55 | else: |
| 56 | pidLine = "%i\n" % self.lockPid |
| 57 | os.write(self.fd, pidLine) |
| 58 | else: # non Windows |
| 59 | self.fp = open(self.lockfile, 'a+') |
| 60 | try: |
| 61 | if self.daemon and self.lockPid != os.getpid(): |
| 62 | fcntl.lockf(self.fp, fcntl.LOCK_EX) # wait for parent to finish |
| 63 | else: |
| 64 | fcntl.lockf(self.fp, fcntl.LOCK_EX | fcntl.LOCK_NB) |
| 65 | self.lockPid = os.getpid() |
| 66 | except IOError: |
| 67 | print 'Another instance of this application is already running' |
| 68 | sys.exit(-1) |
| 69 | else: |
| 70 | pidLine = "%i\n" % self.lockPid |
| 71 | self.fp.truncate(0) |
| 72 | self.fp.write(pidLine) |
| 73 | self.fp.flush() |
| 74 | |
| 75 | def cleanup(self): |
| 76 | if not self.initialized: |