Is there a way to periodically run a Unix command (ps in my case) in Java? The loop I wrote:
while( this.check )
{
try
{
ProcessBuilder pb = new ProcessBuilder("ps");
Process proc;
System.out.println(" * * Running `ps` * * ");
byte[] buffer;
String input;
proc = pb.start();
BufferedInputStream osInput =
new BufferedInputStream(proc.getInputStream());
//prints 0 every time after the first
System.out.println(osInput.available());
buffer = new byte[osInput.available()];
osInput.read(buffer);
input = new String(buffer);
for( String line : input.split("\n"))
{
if( line.equals("") )
continue;
this.handlePS(line);
}
proc.destroy();
try
{
Thread.sleep(10000);
}
catch (InterruptedException ie)
{
ie.printStackTrace();
}
}
catch (IOException ioe)
{
ioe.printStackTrace();
}
}
}
doesn’t work. It runs perfectly fine the first time, but there are 0 bytes available from the input stream every time after that. I’d try the watch command, but this Solaris box doesn’t have that. I can’t use a cron job since I need to know if the PID is there in the Java Application. Any ideas?
Thanks in advance.
EDIT: cannot use cron job
EDIT: I’m making a new Thread of the same type (PS) after it concludes, so I am definitely making a new ProcessBuilder every time.
EDIT: I put the loop that didnt work back in since it caused confusion.
I’m not certain where the loop is, but you will need to create a new
Procobject (and thus a newInputStream) each time through the loop. Otherwise you will always be looking at the result to the first call. The javadocs forProcessBuilderindicate that you do not need to create one of those each time.There may also be a race condition where the input stream is not yet ready when you callk
available(). You should look at making certain that the input stream has reached EOF (which will happen with ps, although not with, say, top) before printing the results.You are also not handling encoding properly, although I don’t know what kind of encoding the output of “ps” is (outside of ASCII). Since “ps” is probably ASCII this is reasonably safe, but may not be for other commands (and for other input streams).