Collect environment variable in java after running script through ProcessBuilder - java

Why does the the following code print false ? I am trying to an environment variable in the test.sh script and collect it in java. Please suggest an alternative approach, if possible.
public static void main(String[] args){
ProcessBuilder processBuilder = new ProcessBuilder("test.sh");
Process process;
int exitCode;
try {
process = processBuilder.start();
exitCode = process.waitFor();
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Map<String, String>envVars = processBuilder.environment();
System.out.println(envVars.keySet().contains("SOURCE"));
}
And the code for test.sh script is simply
set SOURCE=source

The ProcessBuilder.environment() method is used for passing the initial environment to the process when you call start(). You cannot get the environment of a subprocess from a parent process. This is not a Java restriction: you can't even get a subprocess environment from a Bash shell script (or in fact anything) that creates a subprocess. You need to find another means of communicating information from the subprocess back to the parent process.

In my opinion, you should change:
ProcessBuilder processBuilder = new ProcessBuilder("test.sh");
to
ProcessBuilder processBuilder = new ProcessBuilder("/bin/bash", "test.sh");
processBuilder.directory(new File(the-dir-of-test.sh));

Related

How do I get the information of a batch script started in java, whether it has already ended

im calling multiple batch files in Java with the ProcessBuilder like
ProcessBuilder processBuilder = new ProcessBuilder("cmd", "/c", "Start", "batchTest.bat");
File dir = new File(path);
processBuilder.directory(dir);
try {
Process p = pb.start();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Now i want the information that the script is done in java. Like just a sysout when the script is completly finished. process.isAlive() turns false before the script is done. And also process.witFor() doesnt get the job done. Maybe someone has an idea or a workaround?
Okay, i got it. process.waitFor() only works if you add the parameter "/wait" to the Constructor of the ProcessBuilder.
new ProcessBuilder("cmd", "/c", "Start", "/wait", "batchTest.bat");

Processbuilder in Java is not throwing up the sub process exception

I am trying to execute a jar file in Java using ProcessBuilder. Now, Whenever the sub process called by the ProcessBuilder, throws any exception, the ProcessBuilder don't catch the exception and execution keeps on proceeding continuously.
Below is my code:
try {
ProcessBuilder pb = new ProcessBuilder("java", "-jar", CommonConstants.jarFileLocation,
fileEntry.getAbsolutePath(), CommonConstants.commonFileLocation);
Process p = pb.start();
}
catch (Exception e) {
e.printStackTrace();
}
The catch block is suppose to print any exception whenever the sub process throws any. However, it never does.
Am i missing something?
Done it for printing in console....
I used the ProcessBuilder inheritIO method which sets the source and destination for sub process standard I/O to be the same as those of the current Java process.
Hence the modified code...
try {
ProcessBuilder pb = new ProcessBuilder("java", "-jar", CommonConstants.jarFileLocation,
fileEntry.getAbsolutePath(), CommonConstants.commonFileLocation).redirectError(Redirect.INHERIT);
Process p = pb.start();
}
catch (Exception e) {
e.printStackTrace();
}
However, need it to be caught by the catch block.
Need Help!

How to run .sh file, using process builder?

I already create the .sh file, and the inside is:
sudo iptables --flush
sudo iptables -A INPUT -m mac --mac-source 00:00:00:00:00:00 -j DROP
It works normally when I run it on the terminal, but when I use processbuilder, it didn't do anything. No error, but didn't happen anything, this is the code on my java:
Process pb = new ProcessBuilder("/bin/bash","/my/file.sh").start();
I already looking for the answer, but I still failed to run the .sh file, even I do the same thing with people that already done it.
Sorry if this is a bad question, thank you.
Are you sure that the bash is not run? Do you checked the Process object returned by the startmethod? You can get the output value, the output stream, etc. from this objects.
Check your streams and exitvalue for errors... sudo is probably the problem here.
Not necessarily the best code but it gets the job done. Executes a process, takes the process.streams and prints them to System.out. Might helpt to find out what the issue actually is atlest.
ProcessBuilder pb = new ProcessBuilder(args);
pb.redirectErrorStream(true);
final Process proc = pb.start();
final StringBuilder builder = new StringBuilder("Process output");
final Thread logThread = new Thread() {
#Override
public void run() {
InputStream is = proc.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
try {
String line;
do {
line = reader.readLine();
builder.append("");
builder.append(line == null ? "" : line);
builder.append("<br/>");
} while(line != null);
} catch (IOException e) {
builder.append("Exception! ").append(e.getMessage());
} finally {
try {
reader.close();
} catch (IOException e) {
builder.append("Exception! ").append(e.getMessage());
}
}
}
};
logThread.start();
int retVal = proc.waitFor();
System.out.println(builder.toString());
From Java API Runtime : http://docs.oracle.com/javase/7/docs/api/java/lang/Runtime.html
// Java runtime
Runtime runtime = Runtime.getRuntime();
// Command
String[] command = {"/bin/bash", "/my/file.sh"};
// Process
Process process = runtime.exec(command);
Also you should be careful with sudo commands that may ask for root password.

Running a batch file by java

I just wanted to run a batch file using java code in win7. I can run .exe files with the code but u know it doesn't work with a batch. Where is the problem? You know even cmd.exe doesn't start with that command. But I can run other exe files, I've tried some. The code is this (with try and catch is that): none of them worked!
Runtime.getRuntime().exec("cmd.exe /c demo.bat");
Runtime.getRuntime().exec("demo.bat");
i tried to do work with process and i wrote the code below. it retuened
java.lang.IllegalThreadStateException:process has not exited
at java.lang.ProcessImpl.exitValue(Native Method)
at Test.Asli.main(Asli.java:38)
this is the code:
try{
Runtime rt = Runtime.getRuntime();
Process proc= rt.exec("C:\\Windows\\System32\\cmd.exe");
int b = proc.exitValue();
// int exitVal = proc.exitValue();
//System.out.println("Process exitValue: " + exitVal);}
}
catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
Try the following:
String[] cmd = {"cmd.exe", "/c", "demo.bat");
Runtime.getRuntime().exec(cmd);
I always prefer splitting the command and the parameters myself. Otherwise it is done by splitting on space which might not be what you want.
Try this:
Runtime.getRuntime().exec("cmd.exe /c start demo.bat");
Use this:
try {
Process p = Runtime.getRuntime().exec("C:PATH/TO/FILE/yourbatchfile.bat");
} catch(Exception e) {
e.printStackTrace();
}
It even hides the annoying prompt window (if you want that)

Java Swing executing gFortran code

I was wondering is there anyway for Java / Swing code to execute gFortran program on ubuntu/linux platform?
Anyone has some idea on how this could be done ?
One thing you could do is to run a separate program using Runtime to start a Process consisting of your fortran code. The following is an example of this:
Runtime rt = Runtime.getRuntime();
try {
String[] env = {"/path/to/program"};
Process proc = rt.exec("your_program", env);
System.out.println("return value: " + proc.waitFor());
}
catch (Exception ex) {
System.err.println(ex);
}
The above code will execute /path/to/program/your_program and wait for it to finish and then read off the return code.
Alternatively, you could write some information to stdout and read that from your java program:
import java.io.*;
...
Runtime rt = Runtime.getRuntime();
try {
String[] env = {"/path/to/program"};
Process proc = rt.exec("your_program", env);
System.out.println("return value: " + proc.waitFor());
InputStream stream = proc.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
while (reader.ready()) {
// Do something with the data here.
System.out.println(reader.readLine());
}
}
catch (Exception ex) {
System.err.println(ex);
}
If you need to supply the external program with arguments you pass them as an array of strings. As an example, if I wanted to run ls -lh /etc/ that is what the following code does:
String[] cmd = {"ls", "-lh", "/etc/"};
String[] env = {"/bin/"};
Process proc = rt.exec(cmd, env);
You could also try using Java Native Interface to communicate with C/C++ code which can interface with fortran.

Categories

Resources