Process Monitor

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


 * 1) Process Monitor
 * 2) Re-launches a process if it dies.
 * 3) Public Domain
 * 4)   http://en.wikipedia.org/wiki/Public_domain
 * 5) Written by
 * 6)   Atif Aziz, http://www.raboof.com
 * 7) Adapted from
 * 8)   http://bartdesmet.net/blogs/bart/archive/2006/08/30/4366.aspx
 * 9) NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.
 * 1)   http://bartdesmet.net/blogs/bart/archive/2006/08/30/4366.aspx
 * 2) NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.
 * 1) 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

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.