행위

파이썬 데몬 모듈

DB CAFE

thumb_up 추천메뉴 바로가기


1 파이썬 데몬 프로그램 개발[편집]

https://pagure.io/python-daemon/

파이썬으로 데몬 프로그램을 개발시 사용가능한 python-daemon 모듈.

1.1 설치[편집]

  1. pip install python-daemon

1.2 데몬 예제[편집]

python-daemon 을 이용해서 데몬 프로그램을 시작 또는 종료
#!/usr/bin/env python
#-*- coding: utf-8 -*-

import sys
import os
import time
import daemon
from daemon import pidfile

pid_file = '/var/run/domain_test.pid'

def do_something():
    while True:
        time.sleep(2)

def start_daemon():
    print('start_daemon')
    with daemon.DaemonContext(
        working_directory = '/tmp',
        umask = 0o002,
        pidfile = pidfile.TimeoutPIDLockFile(pid_file),
        ) as context:
        do_something()

def main():
    try:
        if sys.argv[1] == 'start':
            start_daemon()

        elif sys.argv[1] == 'stop':
            pid = '999999'

            f = open(pid_file, 'r')

            for line in f:
                pid = line = line.strip()

            f.close()

            cmd = 'kill '+ pid

            os.system(cmd)

    except Exception as e:
        print(e)

if __name__ == "__main__":
    main()
  1. 데몬 프로그램 시작 start 옵션
# ./daemon_test.py start
  1. 확인
#ps auxw | grep daemon_test
  1. 프로그램을 종료 stop 옵션
# ./daemon_test.py stop