This question already has answers here:
How to run Unix shell script from Java code?
(17 answers)
Closed 7 years ago.
I'm trying to execute a shell script from Java.The script is supposed to download the file from the URL using wget.Here goes my code.
public class RunShellScriptFromJava {
public static void main(String a[]) {
try {
ProcessBuilder pb = new ProcessBuilder("/bin/sh","script.sh");
Process p = pb.start();
p.waitFor();
System.out.println("Success");
} catch (Exception e) {
e.printStackTrace();
}
}
}
Content of script.sh
echo "start"
wget http://alex.smola.org/drafts/thebook.pdf
echo "end"
My Question:
Is this the right way doing it?If not please point me in the right direction.It doesn't throw any exception but I see that the file is not getting downloaded.Any lead/help is appreciated.
Thanks.
PS:I have given execute permission for the script
The code sample in the question lacks error handling around the usage of ProcessBuilder, so it's likely that some kind of error happened, but you aren't getting visibility into it.
The return code of Process#waitFor is being ignored. The returned value is the exit code of the spawned process. I recommend checking to see if this value is non-zero.
There is also no handling of stdout or stderr, so you won't know if the spawned process is writing any output that explains what happened. You can access stdout and stderr by using Process#getInputStream and Process#getErrorStream respectively.
Note also that it is possible for your process to hang if it fails to fully consume the streams, or at least redirect them. I've noticed this problem is particularly common on Windows. A standard technique is to spawn background threads to consume the streams. This previous question discusses that technique and others.
Java ProcessBuilder: Resultant Process Hangs
After the error handling in the Java code is enhanced like this, I expect you'll have a better chance of diagnosing what went wrong with the script.
The right way to do this is to use Java to download the file instead of the shell script. The problem with shell scripts is that they are system dependent. By using them you lose one of the main benefits of java which is system independence. There are a number of libraries in Java that will accomplish that functionality. The following will work for you using the FileUtils class from apache IO Commons.
URL url = new URL("http://alex.smola.org/drafts/thebook.pdf");
File download = new File('.');
FileUtils.copyURLToFile(url, download);
This script and java example works, perhaps specify the full path to wget to ensure you know where the pdf is being saved.
$ javac RunShellScriptFromJava.java
$ java RunShellScriptFromJava
Success
$ ls
RunShellScriptFromJava.java thebook.pdf RunShellScriptFromJava.class script.sh
Example/updated script:
wget -O /home/MYSER/test.pdf http://alex.smola.org/drafts/thebook.pdf
My problem is, when I build and run the application using its .jar(distribution ready), this code doesn't work.
filepath = classpath + classname;
ProcessBuilder builder = new ProcessBuilder("javac", filepath + ".java");
builder.redirectErrorStream(true);
process = builder.start();
It works properly when I execute the program using Netbeans. But when it's on its own, it doesn't work.
I'm using ProcessBuilder and Process so that I can get the process' I/O stream later on.
In Netbeans there is a development kit integrated into the environment. Due to this, it will always work with in there. Make sure your environmental variables are set to link to your JDK.
You can try this by going into a cmd.exe window and typing 'javac -version'. If done correctly, it should show the default JDK you have on your system. If it says it can't be found, follow this guide:
http://java.com/en/download/help/path.xml
I am building a GUI in Java (Swing) and I have to execute Java code from that. For the sake of testing simple code like printing HelloWorld in Java will be ok.
I have seen the forum questions and I just know that I have to invoke Operating System (I am using Windows7) to execute that compilation task.
Thank you.
P.S: I have tried with Runtime.getRuntime().exec() command but no success.
If you are using IDE you don't need to call these commands.
Compile:
javac HelloWorldSwing.java
Run:
java HelloWorldSwing
....
If you want to use Runtime.getRuntime().exec(). Here is an example of using Runtime.getRuntime().exec()..
import java.io.*;
public class TestExec {
public static void main(String[] args) {
try {
Process p = Runtime.getRuntime().exec("cmd /C dir");
BufferedReader in = new BufferedReader(
new InputStreamReader(p.getInputStream()));
String line = null;
while ((line = in.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
"This just runs the dir command, captures its ouput and copies it to the programs stdout. Not very exciting but it shows the basic parts to use Runtime.exec(). You can also open up the process' output and error streams. "
so you can send commands with Runtime.getRuntime().exec(), you can use javac or java commands that i have wrote above.
you might want to check out the java compiler api for the compiling code part,
runtime.exec() should work with the correct commands to launch the app.
There is an example of using the JavaCompiler API in the SSCCE Text Based Compiler (STBC). Be sure to read the pages related to getting a tools.jar on the run-time class-path.
The STBC is open source.
For compiling you need an installed JDK which includes the Java compiler javac. You can call javac using via Runtime.getRuntime().exec() for compiling Java source code and then load it.
Alternatively you can use the Java Compiler API. The main compiler API can be retrieved via javax.tools.ToolProvider.getSystemJavaCompiler();
See also this article: The Java 6.0 Compiler API
I have tried running a shell script from a Java program, but the entire script is not being executed. And idea why we might come across such problem?
The Java code to execute shell script:
File file = new File("/path/to/script");
String COMMAND= "./run";
ProcessBuilder p = new ProcessBuilder(COMMAND);
p.directory(file);
try {
Process startProcess= p.start();
} catch (IOException e) {
e.printStackTrace();
}
The script runs fine but not whole script is executed. It seems like only the 1st line is being executed.
If you are sure that the script starts running the problem is not in java but in script itself.
The reason of difference may be the wrong path or wrong environments. When you are running script from console you are in your user's environment, so script can use all environment variables.
Try to add some debug outputs to figure the problem out.
I have a Java program that I'd like to daemonize on a linux system. In other words, I want to start running it in a shell and have it continue running after I've logged out. I also want to be able to stop the program cleanly.
I found this article which uses a combination of shell scripting and Java code to do the trick. It looks good, but I'd like something simpler, if possible.
What's your preferred method to daemonize a Java program on a Linux system?
Apache Commons Daemon will run your Java program as Linux daemon or WinNT Service.
If you can't rely on Java Service Wrapper cited elsewhere (for instance, if you are running on Ubuntu, which has no packaged version of SW) you probably want to do it the old fashioned way: have your program write its PID in /var/run/$progname.pid, and write a standard SysV init script (use for instance the one for ntpd as an example, it's simple) around it. Preferably, make it LSB-compliant, too.
Essentially, the start function tests if the program is already running (by testing if /var/run/$progname.pid exists, and the contents of that file is the PID of a running process), and if not run
logfile=/var/log/$progname.log
pidfile=/var/run/$progname.pid
nohup java -Dpidfile=$pidfile $jopts $mainClass </dev/null > $logfile 2>&1
The stop function checks on /var/run/$progname.pid, tests if that file is the PID of a running process, verifies that it is a Java VM (so as not to kill a process that simply reused the PID from a dead instance of my Java daemon) and then kills that process.
When called, my main() method will start by writing its PID in the file defined in System.getProperty("pidfile").
One major hurdle, though: in Java, there is no simple and standard way to get the PID of the process the JVM runs in.
Here is what I have come up with:
private static String getPid() {
File proc_self = new File("/proc/self");
if(proc_self.exists()) try {
return proc_self.getCanonicalFile().getName();
}
catch(Exception e) {
/// Continue on fall-back
}
File bash = new File("/bin/bash");
if(bash.exists()) {
ProcessBuilder pb = new ProcessBuilder("/bin/bash","-c","echo $PPID");
try {
Process p = pb.start();
BufferedReader rd = new BufferedReader(new InputStreamReader(p.getInputStream()));
return rd.readLine();
}
catch(IOException e) {
return String.valueOf(Thread.currentThread().getId());
}
}
// This is a cop-out to return something when we don't have BASH
return String.valueOf(Thread.currentThread().getId());
}
I frequently find myself writing scripts or command lines which essentially look like this, if I want to:
Run a program that is immune to sighups
That is completely disconnected from the shell which spawns it, and
Produces a log file from stderr and stdout the contents of which are displayed as well, but
Allows me to stop viewing the log in progress and do other stuff without disrupting the running process
Enjoy.
nohup java com.me.MyProgram </dev/null 2>&1 | tee logfile.log &
I prefer the nohup command. The blog post says there are better ways, but I don't think they're enough better.
You could try Java Service Wrapper, the community edition is free and meets your needs.
My preferred way on Ubuntu is to use the libslack 'daemon' utility. This is what Jenkins uses on Ubuntu (which is where I got the idea.) I've used it for my Jetty-based server applications and it works well.
When you stop the daemon process it will signal the JVM to shutdown. You can execute shutdown/cleanup code at this point by registering a shutdown hook with Runtime.addShutdownHook().
That depends. If it's just a one-time thing, I want to daemonize it and then go home, but usually I wait for the results, I might do:
nohup java com.me.MyProgram &
at the command line. To kill it cleanly, you have a lot of options. You might have a listener for SIGKILL, or listen on a port and shutdown when a connection is made, periodically check a file. Difference approaches have different weaknesses. If it's for use in production, I'd give it more thought, and probably throw a script into /etc/init.d that nohups it, and have a more sophisticated shutdown, such as what tomcat has.
DaemonTools :- A cleaner way to manage services at UNIX https://cr.yp.to/daemontools.html
Install daemon tools from the url https://cr.yp.to/daemontools/install.html
follow the instruction mentioned there,for any issues please try instructions https://gist.github.com/rizkyabdilah/8516303
Create a file at /etc/init/svscan.conf and add the below lines.(only required for cent-os-6.7)
start on runlevel [12345]
stop on runlevel [^12345]
respawn
exec /command/svscanboot
Create a new script named run inside /service/vm/ folder and add the below lines.
#!/bin/bash
echo starting VM
exec java -jar
/root/learning-/daemon-java/vm.jar
Note:
replace the Jar with your own Jar file. or any java class file.
Reboot the system
svstat /service/vm should be up and running now !.
svc -d /service/vm should bring vm down now !.
svc -u /service/vm should bring vm up now !.
This question is about daemonizing an arbitrary program (not java-specific) so some of the answers may apply to your case:
Take a look here:
http://jnicookbook.owsiak.org/recipe-no-022/
for a sample code that is based on JNI. In this case you daemonize the code that was started as Java and main loop is executed in C. But it is also possible to put main, daemon's, service loop inside Java.
https://github.com/mkowsiak/jnicookbook/tree/master/recipes/recipeNo029
Have fun with JNI!
nohup java -jar {{your-jar.jar}} > /dev/null &
This may do the trick.