How to invoke sh shell with file using Runtime.getRuntime().exec? - java

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.

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

Use:
Runtime.getRuntime().exec(new String[] { "/bin/bash", "-c", "sh myfile.sh" });

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:
ProcessBuilder to start outer script
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.

Related

Executing shell script from Java

Able to call and execute the shell script when executed in an individual Java Program. But there is no output when called from a Floodlight controller program
The Floodlight controller is executed using java -jar target/floodlight.jar. The command to execute the shell script is provided in one of the source files. When ever the condition matches and code gets executed, the terminal screen appears for a second and vanishes. But this is not the case when I execute the same shell script with Java in an individual program.
Process proc = Runtime.getRuntime().exec(new String[]{"path to shell script", arg1});
Can anybody please comment on this ?
Executing with sudo or in root mode is the culprit.
Ran in user mode, worked perfectly.

Java launch independent process

I have a java app from which I run console based programs on linux system, I am reading the output of those programs and then my java app is sending it to a webpage.
But once I close my java app all the processes will get "stuck" or they just simply crash. So everytime I want to make some changes to my java app and I need to restart it I also have to close all processes that were running from my app. I would like to save their PIDs when closing my app and then take control (output streams) over those processes again based on saved PIDs of the processes.
Is there any way to do it?
I am running my programs like this:
ProcessBuilder processBuilder = new ProcessBuilder(new String[] { "su", "-
s", "/bin/sh", "myuser", "-c", "java -jar myjar.jar" });,
Process p = processBuilder.start();
Edit:
My problem is not finding the process PID my problem is that my subprocesses lanched from my java app are crashing after my java app is closed/terminated and I need them to continue running even while my app is restarting/stopped.
Your problem is due to what is called Unix job control.
Like many shells do, /bin/sh intercepts SIGHUP and SIGINT signals, and before exiting, it sends signals to some of its child processes groups, depending on its configuration and on their state (for instance, stopped background processes receive a SIGCONT).
So, when your main java app is closed, the /bin/sh shell that your app had forked is terminated, and just before exiting, it sends a SIGHUP signal to its subprocesses corresponding to the command java -jar myjar.jar.
So, the answer to your question is: just use the huponexit /bin/sh shell option to avoid killing subprocesses. They will be detached from the controlling terminal, if any, but they will not be killed.
So, replace this java -jar myjar.jar by shopt -u huponexit; java -jar myjar.jar:
ProcessBuilder processBuilder =
new ProcessBuilder(new String[] {
"su", "-s", "/bin/sh", "myuser", "-c",
"shopt -u huponexit; java -jar myjar.jar"
});
Process p = processBuilder.start();
Try to run your command like this:
Runtime.getRuntime().exec("gedit");
It executes the specified string command in a separate process.
Some time ago I have found some useful information here. Try this.
I would use the ps command in Linux to get the number of each process(s) running which you want to control, of course you would execute it just as you have above with your ProcessBuilder. I would then pipe; "|" (Linux Command), the output into a file you have saved somewhere in your Java project.
The Linux command to execute from your Java program would look something a long the lines of
ps -A | grep "your_program_name" > /path/to/your/project/my_process_list_file.txt
Where the > stores the output of the command executed to your file.
I would then read from this file and execute some other Linux commands to take control of that process in whichever way you desire.
Good Luck, and happy coding my friend!

Execute bash command within java program

It's been quite a while since I'm looking for but I don't find the solution. I'm trying to execute bash command on Linux within .jar file.
For that, I tried many things, including this :
Process p = new ProcessBuilder("java", "-jar", "M1_MIAGE_PDL_VIZ_GROUPE3.jar", "menu").start();
Runtime.getRuntime().exec("/bin/sh -c java -jar M1_MIAGE_PDL_VIZ_GROUPE3.jar menu");
Runtime.getRuntime().exec(new String[]{"/bin/sh -c", "java -jar M1_MIAGE_PDL_VIZ_GROUPE3.jar menu"});
So, when I click on the .jar file, I would like to that the program open a bash, and execute the command (java -jar ...), to execute another part of the program.
Any ideas as to how to do it ?
To understand this, you first need to understand how you would run that command at a shell prompt.
$ sh -c "java -jar M1_MIAGE_PDL_VIZ_GROUPE3.jar menu"
Note where the double quotes are. The first argument is -c. The second argument is the stuff inside the quotes; i.e. java -jar M1_MIAGE_PDL_VIZ_GROUPE3.jar menu
Now we translate that into Java:
Process p = new ProcessBuilder(
"/bin/sh",
"-c",
"java -jar M1_MIAGE_PDL_VIZ_GROUPE3.jar menu").start();
Having said that, the above doesn't actually achieve anything. Certainly, it doesn't open a fresh console window to display the console output etcetera. Unlike Windows "CMD.exe", UNIX / Linux shells do not provide console / terminal functionality. For that you need to use a "terminal" application.
For example, if you are using GNOME
Process p = new ProcessBuilder(
"gnome-terminal",
"-e",
"java -jar M1_MIAGE_PDL_VIZ_GROUPE3.jar menu").start();
will (probably) do what you are trying to do.
I think the easiest way to do this would be to create a shell script (.sh extension) and then you can easily run that from within the Java program.
There is a good answer on a previous question on how to run shell scripts within Java here.
To create a shell script you can use any text editor and create a file with the extension .sh and just enter the lines as you would in the bash terminal.

Start a java application with terminal

I'm trying to create a java application which starts a new terminal without using java -jar. I tried using several methods, but none of them have worked.
I need this to work on osx, I was able to make it on windwos
You have to call your shell as a program
Runtime runtime = Runtime.getRuntime();
String[] args = { "/bin/sh", "-c", " java -jar myjar.jar" };
final Process process = runtime.exec(args);
To respond to your specific request, this is my answer
1/ Create a shell script
For example call it loadJava.sh:
#!/bin/sh
java -jar path/to/jar/file.jar
2/ Call the shell script with this java code that open a terminal and run the shell script
Correct code for OSX is
Runtime.getRuntime().exec("/usr/bin/open -a Terminal /path/to/the/script");

Running Shell script on server

I have an Stand alone Application which runs Shell Script(with parameters)in Ubuntu.
ProcessBuilder pb1 = new ProcessBuilder("sh","deltapackage_app.sh","part_value","pathtofile");
Process process1 = pb1.start();
I am taking parameter through GUI.
Now same thing i want to implement in web application where i can take inputs form web page and send it to server and then server will execute the shell script with parameters.
Can any one suggest me the best way of doing this. What things should i use to do this.
I Know i have to learn many things about server. Or can i use same code with Browser based Application.
Consider the following line of code:
Process p = Runtime.getRuntime().exec("/bin/sh -c /bin/ls > ls.out");
This is intended to execute a Bourne shell and have the shell execute
the ls command, redirecting the output of ls to the file ls.out. The
reason for using /bin/sh is to get around the problem of having stdout
redirected by the Java internals. Unfortunately, if you try this
nothing will happen. When this command string is passed to the exec()
method it will be broken into an array of Strings with the elements
being "/bin/sh", "-c", "/bin/ls", ">", and "ls.out". This will fail,
as sh expects only a single argument to the "-c" switch. To make this
work try:
String[] cmd = {"/bin/sh", "-c", "/bin/ls > out.dat"};
Process p = Runtime.getRuntime().exec(cmd);
Since the command line is already a series of Strings, the strings
will simply be loaded into the command array by the exec() method and
passed to the new process as is. Thus the shell will see a "-c" and
the command "/bin/ls > ls.out" and execute correctly.
http://www.ensta-paristech.fr/~diam/java/online/io/javazine.html

Categories

Resources