Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Process stops early even when output is redirected

Tags:

java

process

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?

like image 887
Jeremy Fisher Avatar asked May 24 '26 06:05

Jeremy Fisher


1 Answers

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().

like image 58
Ben Turner Avatar answered May 26 '26 12:05

Ben Turner



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!