Saturday, March 8, 2008

How to timeout any command?

If you ask me what I was doing on 12/23/2002, I can tell you exactly what I was doing. I was busy writing this simple Java program for one of my clients. That's my idea of having fun during holidays :-)


Kidding aside, one of my projects required running a long running process that has to be terminated with in a particular time. I initially thought of writing a timeout module in Perl but my bad, the program should run on Windows boxes and Perl alarm() and signal implementations won't work in Windows. I was just learning Java at the time and thought of giving it a try. It proved surprising simple to write and voila, when I needed to run it on Solaris, it worked there too without any changes. Go Java! (I am not igniting Perl Vs Java war here. It is just that Java is more suitable for this particular requirement).

You can download the source code and compiled Java class from here. The following example shows how to timeout any command with this program. Obviously, you should have Java runtime installed on the computer.

Steps

1) Download the zip file from here.
2) Extract the zip file to a directory, in my case it is C:\venkat\java\bin
3) Run the RunCommand.class using Java runtime.
C:\Venkat\Java\bin> java RunCommand 15 ping myserver

The first argument is the number of seconds to timeout the command. Anything that follows will be treated as a command and its arguments. And the source code is available in RunCommand.java file.

Hope you find this useful. Please feel free to post your questions/comments.

No comments: