simple python daemon

2021. 11. 1. 07:52· Linux/Python
반응형

daemon.py
0.00MB

#!/usr/bin/env python

import sys, os, time, atexit
from signal import SIGTERM 

class Daemon:
	"""
	A generic daemon class.
	
	Usage: subclass the Daemon class and override the run() method
	"""
	def __init__(self, pidfile, stdin='/dev/null', stdout='/dev/null', stderr='/dev/null'):
		self.stdin = stdin
		self.stdout = stdout
		self.stderr = stderr
		self.pidfile = pidfile
	
	def daemonize(self):
		"""
		do the UNIX double-fork magic, see Stevens' "Advanced 
		Programming in the UNIX Environment" for details (ISBN 0201563177)
		http://www.erlenstar.demon.co.uk/unix/faq_2.html#SEC16
		"""
		try: 
			pid = os.fork() 
			if pid > 0:
				# exit first parent
				sys.exit(0) 
		except OSError, e: 
			sys.stderr.write("fork #1 failed: %d (%s)\n" % (e.errno, e.strerror))
			sys.exit(1)
	
		# decouple from parent environment
		os.chdir("/") 
		os.setsid() 
		os.umask(0) 
	
		# do second fork
		try: 
			pid = os.fork() 
			if pid > 0:
				# exit from second parent
				sys.exit(0) 
		except OSError, e: 
			sys.stderr.write("fork #2 failed: %d (%s)\n" % (e.errno, e.strerror))
			sys.exit(1) 
	
		# redirect standard file descriptors
		sys.stdout.flush()
		sys.stderr.flush()
		si = file(self.stdin, 'r')
		so = file(self.stdout, 'a+')
		se = file(self.stderr, 'a+', 0)
		os.dup2(si.fileno(), sys.stdin.fileno())
		os.dup2(so.fileno(), sys.stdout.fileno())
		os.dup2(se.fileno(), sys.stderr.fileno())
	
		# write pidfile
		atexit.register(self.delpid)
		pid = str(os.getpid())
		file(self.pidfile,'w+').write("%s\n" % pid)
	
	def delpid(self):
		os.remove(self.pidfile)

	def start(self):
		"""
		Start the daemon
		"""
		# Check for a pidfile to see if the daemon already runs
		try:
			pf = file(self.pidfile,'r')
			pid = int(pf.read().strip())
			pf.close()
		except IOError:
			pid = None
	
		if pid:
			message = "pidfile %s already exist. Daemon already running?\n"
			sys.stderr.write(message % self.pidfile)
			sys.exit(1)
		
		# Start the daemon
		self.daemonize()
		self.run()

	def stop(self):
		"""
		Stop the daemon
		"""
		# Get the pid from the pidfile
		try:
			pf = file(self.pidfile,'r')
			pid = int(pf.read().strip())
			pf.close()
		except IOError:
			pid = None
	
		if not pid:
			message = "pidfile %s does not exist. Daemon not running?\n"
			sys.stderr.write(message % self.pidfile)
			return # not an error in a restart

		# Try killing the daemon process	
		try:
			while 1:
				os.kill(pid, SIGTERM)
				time.sleep(0.1)
		except OSError, err:
			err = str(err)
			if err.find("No such process") > 0:
				if os.path.exists(self.pidfile):
					os.remove(self.pidfile)
			else:
				print str(err)
				sys.exit(1)

	def restart(self):
		"""
		Restart the daemon
		"""
		self.stop()
		self.start()

	def run(self):
		"""
		You should override this method when you subclass Daemon. It will be called after the process has been
		daemonized by start() or restart().
		"""
저작자표시 (새창열림)

'Linux > Python' 카테고리의 다른 글

pid handle  (0) 2021.10.31
Python argument vscode debug  (0) 2021.10.30
Python socket(Ping3, Ping) 관련 Permisson Error 해결  (0) 2021.10.26
Python을 이용한 RAID상태 모니터링  (0) 2019.04.15
'Linux/Python' 카테고리의 다른 글
  • pid handle
  • Python argument vscode debug
  • Python socket(Ping3, Ping) 관련 Permisson Error 해결
  • Python을 이용한 RAID상태 모니터링
zosystem
zosystem
몇 달만 지나도 가물가물해서 만든 곳
zosystem
동방노트
zosystem manage
전체
오늘
어제
  • 분류 전체보기 (278)
    • Linux (90)
      • 기본명령어&팁 (13)
      • 설치 및 셋팅 (16)
      • 네트워크보안 (5)
      • Samba&NFS (6)
      • 모니터링 (3)
      • Apache&nginx (5)
      • MySQL (2)
      • PHP (0)
      • Cloud (29)
      • Shell (1)
      • RAID (1)
      • PLEX (2)
      • Python (5)
      • Docker (2)
    • Windows (22)
    • Windows Server (9)
    • IoT (1)
    • 데이타베이스 (1)
    • 잡다한 개발팁 (19)
    • 개발유틸리티 (8)
    • 컴퓨터관리 (127)

블로그 메뉴

  • 홈

공지사항

인기 글

태그

  • 프린터
  • 그래픽카드 드라이버 이슈
  • amd 드라이버 이슈
  • fail2ban
  • RDP
  • OpenMediaVault
  • 시놀로지 그누보드5 설치
  • phpmyadmin 접근제어
  • mysql_connect() error
  • PID
  • rsync
  • 프린터 방화벽
  • openmediavault 7
  • nt530u4e-e3b
  • 바탕 화면 아이콘 설정 단축키
  • ap
  • portainer
  • synology phpmyadmin
  • CCTV
  • docker
  • log syntax highlighting
  • fpc케이블
  • OMV
  • IP Camera
  • selenium
  • synology firewall
  • 원격 데스크톱 연결
  • Python
  • Printer
  • omv7

최근 댓글

최근 글

hELLO · Designed By 정상우.v4.2.1
zosystem
simple python daemon
상단으로

티스토리툴바

단축키

내 블로그

내 블로그 - 관리자 홈 전환
Q
Q
새 글 쓰기
W
W

블로그 게시글

글 수정 (권한 있는 경우)
E
E
댓글 영역으로 이동
C
C

모든 영역

이 페이지의 URL 복사
S
S
맨 위로 이동
T
T
티스토리 홈 이동
H
H
단축키 안내
Shift + /
⇧ + /

* 단축키는 한글/영문 대소문자로 이용 가능하며, 티스토리 기본 도메인에서만 동작합니다.