user1015721
user1015721

Reputation: 149

Can I get a Java app to wait for background processes to complete?

I have a bash script sitting on a server and a Java app that will run on said server. My goal is to invoke this script, twice, from the Java app such that both will run concurrently.

I have the following code:

Runtime runtime = Runtime.getRuntime();
Process process = runtime.exec(new String[] { "/bin/bash", "-c", "script.sh & script.sh & " });

This should invoke the script via bash, run it in the background, and then immediately set off another one before the first finishes (the script takes about ten seconds to run). This all seems to work perfectly fine.

The problem is, I then want to wait until both background processes have completed before moving on to the next line in my Java program. I tried this:

int exitValue = process.waitFor();
// "next line of code"

However, it seems that "next line of code" is running before both processes have really finished. I suspect that what is happening is that Java considers the "process" complete as soon as the second process is kicked off since they are both run in the background. My guess is that process.waitFor() is really only good for tracking foreground processes.

I suppose one solution would be to make a temporary bash script that kicks off both processes in the background, run that script in the foreground, and track its progress with process.waitFor(). But I would really prefer not having to keep creating temporary scripts that call other scripts just so that it can run in the foreground. Ideally I would like invoke the background processes the way I am today and simply wait until they are all done. I don't know if this is possible.

Upvotes: 0

Views: 1122

Answers (2)

fdsa
fdsa

Reputation: 1409

You could have each of these run in a child thread and then "join" these threads.

Runnable run1 = new Runnable()
{
    public void run()
    {
        Runtime runtime = Runtime.getRuntime();
        Process process = runtime.exec(new String[] { "/bin/bash", "-c", "script.sh & script.sh & " });
    }
}

Runnable run2 = new Runnable()
{
        Runtime runtime = Runtime.getRuntime();
        Process process = runtime.exec(new String[] { "/bin/bash", "-c", "script2.sh & script2.sh & " });

}

Thread thread1 = new Thread(run1);
Thread thread2 = new Thread(run2);

thread1.start();
thread2.start();

thread1.join();
thread2.join();

Upvotes: 1

ch271828n
ch271828n

Reputation: 17643

I think you may not create a background bash command in your case. The & is for command running in background, which will let the real work be running in background but tell you the shell is done.

Runtime runtime =  Runtime.getRuntime(); 
Process process = runtime.exec(new String[] { "/bin/bash", "-c", "script.sh & script.sh " });

Upvotes: 0

Related Questions