Skip to content

Instantly share code, notes, and snippets.

@kelson-martins
Last active October 2, 2017 10:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kelson-martins/6b49ff5bce478aea1b8f1e99723aa4c2 to your computer and use it in GitHub Desktop.
Save kelson-martins/6b49ff5bce478aea1b8f1e99723aa4c2 to your computer and use it in GitHub Desktop.
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