Last active
October 2, 2017 10:32
-
-
Save kelson-martins/6b49ff5bce478aea1b8f1e99723aa4c2 to your computer and use it in GitHub Desktop.
Using Python pid to controll processes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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