import os
import sys
import subprocess
from subprocess import Popen
from enum import Enum
from time import sleep, localtime, strftime
from threading import Thread
import tempfile
import getpass
from casa_shutdown import add_shutdown_hook
class output_option(Enum):
PIPE = 1
STDOUT = 2
DISCARD = 3
class procmgr(Thread):
from procmgr import output_option
class proc(Thread):
def __init__(self, tag, cmd, output=output_option.DISCARD):
""" tag: identification for this process
cmd: list of strings representing the command followed by the arguments
output: disposition of output STDOUT, PIPE, DISCARD (default is to discard output)"""
Thread.__init__(self)
self.tag = tag
self.pid = None
self.stderr = None
self.stdout = None
self.stdin = None
self.__cmd = cmd
self.__output_option = output
self.__running = False
self.__proc = None
self.__watchdog = None
def stop(self):
""" stop( ) -> None
stops the process if it is running"""
if self.__running:
self.__running = False
if self.__proc and self.__proc.poll( ) == None:
try:
self.__proc.terminate()
sleep(0.5)
if self.__proc.poll( ) is None:
print "%s => proc %s is being killed" % (strftime("%y-%m-%d %H:%M:%S", localtime()), self.tag)
self.__proc.kill()
if self.__watchdog.poll( ) is None:
self.__watchdog.kill()
except OSError:
pass
def running(self):
""" running( ) -> Bool
check to see if the process is still running"""
return self.__running
def run(self):
""" run( ) -> None
start the process"""
self.stop( )
if self.__output_option is output_option.PIPE:
out = subprocess.PIPE
elif self.__output_option is output_option.STDOUT:
try:
out = os.fdopen(sys.stdout.fileno(), 'a', 0)
except:
out = os.fdopen(1,'a',0)
else:
out = file(os.devnull,'a')
self.__proc = Popen( self.__cmd, stderr=out, stdout=out, stdin=subprocess.PIPE )
self.__watchdog = Popen( [ '/bin/bash','-c',
'while kill -0 %d > /dev/null 2>&1; do sleep 1; kill -0 %d > /dev/null 2>&1 || kill -9 %d > /dev/null 2>&1; done' % \
(self.__proc.pid, os.getpid( ), self.__proc.pid) ] )
self.stdin = self.__proc.stdin
self.pid = self.__proc.pid
if self.__output_option is output_option.PIPE: