Skip to content

Instantly share code, notes, and snippets.

@nobonobo
Last active August 29, 2015 14:27
Show Gist options
  • Select an option

  • Save nobonobo/90154e763edb6fcce440 to your computer and use it in GitHub Desktop.

Select an option

Save nobonobo/90154e763edb6fcce440 to your computer and use it in GitHub Desktop.
スクリプト本体をファイルロックして多重起動抑止するタイムアウト付きサンプル。
import sys
import time
import signal, errno
from contextlib import contextmanager
import fcntl
@contextmanager
def timeout(seconds):
def timeout_handler(signum, frame):
pass
original_handler = signal.signal(signal.SIGALRM, timeout_handler)
try:
signal.alarm(seconds)
yield
finally:
signal.alarm(0)
signal.signal(signal.SIGALRM, original_handler)
with timeout(1):
f = open("sample.py")
try:
fcntl.flock(f.fileno(), fcntl.LOCK_EX)
except IOError as e:
if e.errno != errno.EINTR:
raise e
print("Lock timed out")
sys.exit(1)
time.sleep(10)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment