Process Monitor

From IronPython Cookbook

The following code demonstrates how to write a small utility in IronPython that monitors a process and re-launches it if it dies.

# Process Monitor
#
# Re-launches a process if it dies.
#
# Public Domain
#   http://en.wikipedia.org/wiki/Public_domain
# Written by 
#   Atif Aziz, http://www.raboof.com
# Adapted from
#   http://bartdesmet.net/blogs/bart/archive/2006/08/30/4366.aspx
#
# NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.

import sys
from System import Console
from System.Diagnostics import Process, ProcessStartInfo

def launch(binpath, args):    
    psi = ProcessStartInfo(FileName = binpath, Arguments = args)
    proc = Process(StartInfo = psi, UseShellExecute = False, EnableRaisingEvents = True)
    def onexit(sender, event_args):
        print 'Process %d stopped. Re-starting...' % proc.Id
        launch(binpath, args)
    proc.Exited += onexit
    proc.Start()
    print 'Process %d started' % proc.Id

def main(args):
    if not args:
        raise Exception('Missing binpath to executable.')
    launch(args[0], ' '.join(['"%s"' % arg for arg in args[1:]]))
    Console.ReadLine()
    
if __name__ == '__main__':
    main(sys.argv[1:])

Recommended Usage (Windows)

The recommended way to try the above code is to save it in a file named procmon.py. In the same directory as procmon.py, create a batch file called procmon.bat and place the following text in there:

@ipy "%~dpn0.py" %*

This assumes that the console version of the IronPython executable (ipy.exe) is in your PATH environment variable. Next, just type procmon notepad.exe on the Command Prompt. If you close the launched Notepad instance then a new one will be launched shortly after. This will keep happening until the IronPython script is stopped by simply pressing ENTER at its console.

See also: Deployment#Batch Files

Sample Output

Below is an example of what the output from the IronPython script could look like. Notice that three question marks (???) where the owner could not be determined.

C:\>procmon notepad.exe
Process 1440 started
Process 1440 stopped. Re-starting...
Process 4884 started
Process 4884 stopped. Re-starting...
Process 5644 started
Process 5644 stopped. Re-starting...
Process 5820 started

Back to Contents.

TOOLBOX
LANGUAGES