Skip to content

Instantly share code, notes, and snippets.

@imrehg
Last active July 14, 2016 06:16
Show Gist options
  • Select an option

  • Save imrehg/920ee85e6c6991aa50cd19b7644aa66c to your computer and use it in GitHub Desktop.

Select an option

Save imrehg/920ee85e6c6991aa50cd19b7644aa66c to your computer and use it in GitHub Desktop.
Example of a script being able to hand-over to a second instance of itself
"""
Python `hand-over` strategy example
"""
import os
import sys
import socket
SOCKFILE = "/tmp/handover.sock"
# Check for this script already running
# by trying to receive one byte of data over the socket
try:
client = socket.socket(socket.AF_UNIX,
socket.SOCK_STREAM)
client.connect(SOCKFILE)
client.recv(1)
except socket.error:
pass
# Remove socket if already exists since now we are
# the only code that runs after the previous check
if os.path.exists(SOCKFILE):
os.remove(SOCKFILE)
# Recreate socket
server = socket.socket(socket.AF_UNIX,
socket.SOCK_STREAM)
server.bind(SOCKFILE)
server.listen(5)
server.setblocking(False)
def heavylifting():
""" Main task to run within this application
"""
i = 0
while True:
print("Doing some work, count to {}".format(i))
i += 1
# Handover check
try:
# Try to send data over the socket
conn = server.accept()[0]
conn.close()
break
except socket.error:
# Other end of socket not connected,
# continue looping
pass
# Run the main task in a loop
heavylifting()
###
# Release resources for handover:
# * Close file handles
# * Close serial port
# * ...
#
# In the real application finally create this file
# to signal being ready to retire:
# open('/data/resin-kill-me', 'w+').close()
###
# Exit
# Force exit all threads
sys.exit(0)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment