Last active
August 29, 2015 14:27
-
-
Save nobonobo/90154e763edb6fcce440 to your computer and use it in GitHub Desktop.
スクリプト本体をファイルロックして多重起動抑止するタイムアウト付きサンプル。
This file contains hidden or 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
| 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