1

How to invoke sh file in linux terminal using Runtime.getRuntime().exec in java ?

I want to invoke the sh file in new terminal from java code. If i run it in terminal only it runs as a separate process, which will not be closed even if my programs exits. And thats why I'm not using ProcessBuilder, which stops the process invoked by it if the program using it exits.

jww
  • 97,681
  • 90
  • 411
  • 885
merlachandra
  • 376
  • 2
  • 17
  • possible duplicate of [Runtime.getRunTime().exec not behaving like C language "system()" command](http://stackoverflow.com/questions/7665185/runtime-getruntime-exec-not-behaving-like-c-language-system-command) – jtahlborn Jul 25 '13 at 12:49
  • What you have to do is run a terminal emulator, passing the script as a parameter. Which terminal emulator do you use? Xterm, gnome-terminal, konsole, ... ? – Joni Jul 25 '13 at 12:54
  • 1
    possible duplicate of [How do I launch a completely independent process from a Java program?](http://stackoverflow.com/questions/931536/how-do-i-launch-a-completely-independent-process-from-a-java-program) – Aaron Digulla Jul 25 '13 at 13:00

3 Answers3

0

If your script is marked as executable (chmod +x script.sh), you can invoke it by exec("./script.sh"). Otherwise you can directly call it using exec("sh script.sh").

Bengt
  • 3,798
  • 2
  • 21
  • 28
0

Use:

Runtime.getRuntime().exec(new String[] { "/bin/bash", "-c", "sh myfile.sh" });
Ankur Lathi
  • 7,636
  • 5
  • 37
  • 49
0

Since ProcessBuilder is just a thin wrapper around Runtime, using it directly will not do what you want.

Instead, you need to write a second script which creates a terminal window as a background process and detaches this process. General approach:

  1. ProcessBuilder to start outer script
  2. Outer script uses the Linux command nohup(1) to create a detached process for inner script. For example: `nohup xterm -e /bin/bash "script.sh &"

nohup cuts the connections between the new X terminal and the Java process. & sends the whole thing into the background, so the command doesn't until xterm exits.

Aaron Digulla
  • 321,842
  • 108
  • 597
  • 820