File: runOnce.py

package info (click to toggle)
clam 1.4.0-5.1
  • links: PTS, VCS
  • area: main
  • in suites: wheezy
  • size: 17,780 kB
  • sloc: cpp: 92,499; python: 9,721; ansic: 1,602; xml: 444; sh: 239; makefile: 153; perl: 54; asm: 15
file content (39 lines) | stat: -rwxr-xr-x 952 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#!/usr/bin/python
import sys
if len(sys.argv) < 3 :
	print """
This script launches a commandline just if it can adquire a given lock
file. It can be used to avoid duplicated instances of an application.
$ runOnce.py /path/to/the/lock/file.lock program arg1 arg2....
"""
	sys.exit(-1)

import os

class FileLock :
	def __init__(self, filename) :
		try:
			self.filename = filename
			self.lockfd = os.open(filename, os.O_RDWR|os.O_EXCL|os.O_CREAT)
			os.write(self.lockfd, str(os.getpid()))
		except OSError:
			self.lockfd = None
	def wasAdquired(self): return not self.lockfd is None
	def __del__(self) :
		if not self.lockfd : return
		os.close(self.lockfd)
		os.remove(self.filename)

import time
import sys
import subprocess
lockfile = sys.argv[1]
command = sys.argv[2:]
lock = FileLock(lockfile)
if lock.wasAdquired() :
	subprocess.call(command)
	del lock
	sys.exit()

print "Already running. Remove the file %s if you think it is not"%lockfile