#!/usr/bin/env python

# This file goes in <SAGE_ROOT>/local/bin/sage-monitor

import os, sys, time

def check_usage():
    v = sys.argv
    if len(v) != 4:
        print "Usage: sage-monitor <master pid> <subprocess pid> <interval>"
        print "Runs the shell command checking every interval seconds"
        print "to see if there is a process with the given master pid."
        print "If not kill -9 the given subprocess pid and terminate."
        print "Also, if the subprocess vanishes, then this program exits."
        sys.exit(1)

def process_is_running(pid):
    print "determine if %s is running"%pid
    sys.stdout.flush()
    try:
        os.kill(pid,0)
    except OSError:
        # This means the process is not running
        return False
    return True

def main():
    v = sys.argv
    pid = int(v[1])
    subprocess = int(v[2])
    interval = int(v[3])

    while True:
        time.sleep(interval)
        if not process_is_running(pid):
            try:
                os.killpg(subprocess, 9)
            except OSError, msg:
                print msg
            try:
                os.kill(subprocess, 9)
            except OSError, msg:
                print msg
            sys.exit(0)
        #end if
        if not process_is_running(subprocess):
            sys.exit(0)

if __name__ == '__main__':
    check_usage()
    main()
    
