0

I have written a simple program to run a shell script in Ubuntu box using java process. The script usually takes around 3 minutes to complete when executed manually. So, to cope with that, I have given 1 extra minute in the function process.waitFor(4, TimeUnit.MINUTES); Now, the problem is that the code works just fine when I compile and run the code manually, but when I am using this same code in a spring mvc project, it gets stuck at getRuntime().exec("bash /home/username/script.sh"); It is not throwing any errors. I am running this program directly in my controller. I am stuck at it as I need to run one more script after I run this script successfully. Below is my complete code:

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.concurrent.TimeUnit;

public class Test{
    public static void main(String[] args){
        try{
            StringBuffer output = new StringBuffer();
            Process p;
            System.out.println("Before Runtime");
            p = Runtime.getRuntime().exec("bash /home/username/script.sh");
            System.out.println("After Runtime.exec");
            p.waitFor(4, TimeUnit.MINUTES);
            System.out.println("After p.waitFor()");
            BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
            BufferedReader errReader = new BufferedReader(new InputStreamReader(p.getErrorStream()));
            String line = "";
            while ((line = errReader.readLine()) != null) {
                output.append(line + "\n");
                System.out.println("ErrorLine: "+ line);
            }
            while ((line = reader.readLine()) != null) {
                output.append(line + "\n");
                System.out.println(line);
            }
        }catch(IOException | InterruptedException e){
            System.out.println("Error: "+e.getMessage());
        }
    }
}

I am doing everything on ubuntu box.
Do anyone know where the problem is?

Shubham Sharma
  • 133
  • 2
  • 11
  • You are waiting for process completion *before* you consume the process output, however the process likely produces a fair amount of output, so the output buffer runs full. The process is waiting for you to consume output and make room for more, and you're waiting for the process to complete. *Deadlock!!* – Andreas May 17 '18 at 15:49
  • What is the wait for? Generally using a wait is a very bad solution to any issue you may be having. Have you tried out something like this: https://stackoverflow.com/questions/26830617/java-running-bash-commands – Adam May 17 '18 at 15:49

0 Answers0