Jeremy Fisher
Jeremy Fisher

Reputation: 2782

Java Process stops early even when output is redirected

I have a Java application that calls a tcsh script which in turn calls a perl script in the same directory. If I run this script from the command by typing "runPerlScript.sh", it works completely fine, and generates several output files as it should. However, if I call the script from Java, using the code below:

    String[] runCmd  = {"/bin/tcsh","-c","/filepath/runPerlScript.sh"};
    Process run = Runtime.getRuntime().exec(runCmd);

    BufferedReader reader = new BufferedReader(new InputStreamReader(run.getInputStream()));

    String line = "";
    line = reader.readLine();
    System.out.println("\nStarting while.");
    while((line)!=null){
        System.out.println("Output from script: "+line);
        line=reader.readLine();
    }
    reader.close();
    System.out.println("Finished running perl script.");

it prints out the echo statements from my shell script to my console (I'm using NetBeans), but generates only 4 output files (when normally it generates near 50). It seems as if the process is quitting to early, because after these 4 files are generated, an echo statement in my shell script that says "Finished running runPerlScript.sh" prints out to my console. I've tried several different ways to run this script, including ProcessBuilder, but none seem to generate the output files. The code I have above was in fact the only way I was able to generate ANY output, because ProcessBuilder just resulted in hangups. Does anyone know how I can continuously make the script run?

Upvotes: 3

Views: 588

Answers (1)

Ben Turner
Ben Turner

Reputation: 131

From the Runtime.exec() javadoc:

"Executes the specified string command in a separate process."

Assuming you want to wait for the process to end, you will need to wait for the process to terminate in your main java thread. The best way to do this would be by monitoring the Process returned by ProcessBuilder.start() and wait with Process.waitFor().

Upvotes: 1

Related Questions