Instantly share code, notes, and snippets.

Embed
What would you like to do?
Using Python pid to controll processes
#!/usr/bin/python
import os
import time
import signal
# Get process PID
PID = str(os.getpid())
PIDFILE = "RUNNING.pid"
def can_it_run():
# Check wether lock PIDFILE exists
if os.path.isfile(PIDFILE):
return False
else:
return True
def run():
# Write lock file containing process PID
file(PIDFILE, 'w').write(PID);
print "Executing under PID " + PID
try:
# Simulating miscellaneous tasks
time.sleep(60)
finally:
# removing lock file upon script execution
os.unlink(PIDFILE)
if __name__ == '__main__':
if can_it_run():
run();
else:
# Retrieving PID of previous execution
old_pid = ''.join(file("RUNNING.pid"))
print "Script already running under PID %s, which is now being terminated." % old_pid
# forcing a new execution by killing old process
os.kill(int(old_pid),signal.SIGTERM)
run()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment