1

I am developing a web application in which I am using Java as my front end and shell as my back end . I am processing lot of files in shell .. for instance if I have to process 100 files . I am planning to spawn 4 sub processes from Java application. I read about process Builder . But I am not getting a clear idea of how to use the start() method to spawn multiple processes and then wait for all of them until it is done and again continuing processing . Any ideas reagrding this would be highly useful to me. Thank you.

1 Answer 1

2

Generally speaking, start will call Runtime.exec(...) on your behalf.

Once running (off in it's own little process), you can interact with the it via the processes input and output streams.

In my own work, I monitor the input and error streams. I do this by spawning a new thread for each stream and monitor the through put via the stream.read() method and look for a return result of -1 to determine when the streams have completed.

I use a third "monitor" thread which is used to provide "waitFor" functionality and help clean up the stream threads.

I would recommend at least reading the input and error streams in seperate threads as this allows you to monitor the process without blocking your current thread context.

If you want to wait for the process to exit, you should use Process.waitFor() (the process is returned to you by the ProcessBuilder.start() method). This will wait for the process to exit. This method will return the exit code for the process which can be useful to respond to errors that the process may want to tell you about.

Okay, so in short...

ProcessBuilder pb = new ProcessBuilder(new String[] {cmd, parameter1, parameter2, ...});
Process process = pb.start();

InputStream is = process.getInputStream();
InputStream isErr process.getErrorStream();

// Spawn some threads to process the streams

int exitValue = process.waitFor();

if (exitValue == 0) {

    System.out.println("All is good with the world");

} else {

    // Handle error     

}
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for your help.. Now my problem is I have an awk script inside the shell script that I am calling ... The thing is, this awk script is not being executed when I call the shell script.. Wat might be this problem ...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.