Last active
December 9, 2015 09:20
-
-
Save Junzki/76b7f1b9baa8225736fd to your computer and use it in GitHub Desktop.
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
# -*- coding:utf-8 -*- | |
import os | |
import sys | |
import atexit | |
import signal | |
import codecs | |
def daemonize(pidfile, stdin='/dev/null', | |
stdout='/dev/null', | |
stderr='/dev/null'): | |
if os.path.exists(pidfile): | |
raise RuntimeError('Already Running') | |
try: | |
if os.fork() > 0: | |
raise SystemExit(0) | |
except OSError as e: | |
raise RuntimeError('Fork #1 failed.') | |
os.chdir('/') | |
os.umask(0) | |
os.setsid() | |
try: | |
if os.fork() > 0: | |
raise SystemExit(0) | |
except OSError as e: | |
raise RuntimeError('Fork #2 failed.') | |
sys.stdout.flush() | |
sys.stderr.flush() | |
_stdin = codecs.open(stdin, 'r', encoding='utf-8') | |
os.dup2(_stdin.fileno(), sys.stdin.fileno()) | |
_stdout = codecs.open(stdout, 'w+', encoding='utf-8') | |
os.dup2(_stdout.fileno(), sys.stdout.fileno()) | |
_stderr = codecs.open(stderr, 'w+', encoding='utf-8') | |
os.dup2(_stderr.fileno(), sys.stderr.fileno()) | |
with codecs.open(pidfile, 'w', encoding='utf-8') as f: | |
f.write(str(os.getpid())) | |
atexit.register(lambda: os.remove(pidfile)) | |
def sigterm_handler(signo, frame): | |
raise SystemExit(1) | |
signal.signal(signal.SIGTERM, sigterm_handler) | |
def main(): | |
sys.stdout.write('Daemon start with PID {}\n'.format(os.getpid())) | |
''' | |
Call what you want to daemonize here. | |
''' | |
def execute_from_cli(argv): | |
PIDFILE = '/path/to/your/pid/file.pid' | |
if len(argv) != 2: | |
print('Usage : {} [start|stop]'.format(argv[0], file=sys.stderr)) | |
raise SystemExit(1) | |
if argv[1] == 'start': | |
try: | |
daemonize(PIDFILE, stdout='/path/to/redirect/stdout', | |
stderr='/path/to/redirect/stderr') | |
except RuntimeError as e: | |
sys.stderr.write(e.message) | |
raise SystemExit(1) | |
main() | |
elif argv[1] == 'stop': | |
if os.path.exists(PIDFILE): | |
with codecs.open(PIDFILE, 'r', encoding='utf-8') as f: | |
os.kill(int(f.read()), signal.SIGTERM) | |
else: | |
with codecs.open(sys.stderr) as f: | |
f.write('Not running.') | |
raise SystemExit(1) | |
else: | |
print('Unknown command {!r}'.format(sys.argv[1], file=sys.stderr)) | |
raise SystemExit(1) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment