﻿import os
import subprocess, os, sys, signal, subprocess
from aquests.lib import flock

class Process:
	def __init__ (self, cmd, name, vardir = None):
		self.cmd = cmd
		self.name = name
		self.vardir = vardir		
		self.child = None
		if os.name == "nt":
			self.flock = flock.Lock (os.path.join (self.vardir, "lock.%s" % self.name))			
		self.create ()
	
	def create (self):	
		if os.name == "nt":
			self.child = subprocess.Popen (
				self.cmd, 
				shell = True,
				creationflags = subprocess.CREATE_NEW_PROCESS_GROUP
			)							
		else:
			self.child = subprocess.Popen (
				"exec " + self.cmd, 
				shell = True
			)

	def send_signal (self, req):
		if req == "start": 
			req = "restart"
		else:
			if req not in ("terminate", "kill", "restart", "rotate"):
				print("[error] unknown command")
				sys.exit (1)
		
		pid	 = self.child.pid
		if os.name == "nt":		
			self.flock.lock ("signal", req)
			if req == "terminate":
				os.kill (pid, signal.CTRL_C_EVENT)
			elif req == "kill":	
				os.kill (pid, signal.CTRL_BREAK_EVENT)
	
		else:			
			if pid:					
				if req == "terminate": sig = signal.SIGTERM				
				elif req == "kill": sig = signal.SIGKILL
				elif req == "restart": sig = signal.SIGHUP				
				elif req == "rotate": sig = signal.SIGUSR1
				os.kill (pid, sig)
			elif req == "restart":
				self.flock.lock ("signal", req)
			
	def kill (self):
		self.send_signal ("terminate")
	
	def poll (self):
		return self.child.poll ()
		
@@ -899,16 +899,20 @@
 %22, req)%0A
+%09%09%09%0A
 %09%09%09if re
@@ -929,37 +929,29 @@
 inate%22:%0A%09%09%09%09
-os.kill (pid,
+sig =
  signal.CTRL
@@ -958,17 +958,16 @@
 _C_EVENT
-)
 %0A%09%09%09elif
@@ -983,37 +983,29 @@
 kill%22:%09%0A%09%09%09%09
-os.kill (pid,
+sig =
  signal.CTRL
@@ -1016,18 +1016,96 @@
 AK_EVENT
-)
 %0A
+%09%09%09%0A%09%09%09try:%0A%09%09%09%09os.kill (pid, sig)%0A%09%09%09except ProcessLookupError:%0A%09%09%09%09pass%09%0A%09%09%09%09
 %09%0A%09%09else
@@ -1320,16 +1320,26 @@
 SIGUSR1%0A
+%09%09%09%09try:%0A%09
 %09%09%09%09os.k
@@ -1349,24 +1349,72 @@
  (pid, sig)%0A
+%09%09%09%09except ProcessLookupError:%0A%09%09%09%09%09pass%0A%09%09%09%09%09%09%0A
 %09%09%09elif req 

handle KeyboardInterrupt on posix