Cannot run exe file with ProcessBuilder in Java - java

I am trying to run an exe file while setting some parameters for it like this:
myExePath -ini myIniPath -x myConfigFilePath
When I run it from the command line it works perfectly. But when I try running it from my Java code the process starts but after a while is not responding anymore so I have to forcibly close it. I am using this Java code:
List<String> parameters = new ArrayList<String>();
parameters.add(myexePath);
parameters.add("-ini ");
parameters.add(myIniPath);
parameters.add("-x ");
parameters.add(myConfigPath
ProcessBuilder builder = new ProcessBuilder(parameters);
Process process = builder.start();
try {
process.waitFor();
} catch (InterruptedException e) {
System.err.println("Process was interrupted");
}
Any ideas what I am doing wrong?

Does the exe use stdout, stderr, stdin? You should always read from them or close them. Depending on the implementation and buffer size not reading from them could lead to blocking.

I'm not sure if it helps, but why you use spaces?
e.g.: parameters.add("-x ");
You don't need them.
What you can also try is to put all your parameters in an array and use another constructor of ProcessBuilder which takes an array as argument.

I guess you should first get a reference to the Runtime.
You could do this
Runtime.getRuntime().exec(parameters.toString());
Your string from the parameters list may need a bit formatting.

Related

Java Process Builder not executing multiple commands

Hi a Java newbie here.
I am currently building a Java application that executes multiple linux commands with Java Process builder.
I am planning to execute a shell scipt, and since it this shell script is an external program that takes about a second to fully execute, let the process sleep for a second and write the result into a txt file.
This is an external program and it must take in "q" to exit the program, so I finally need to type in q in the terminal.
I have gotten help on this community before and the code I constructed with that help is as follows.
public static void Linux(String fileName){
try {
File dir = new File("/usr/local/bin");
ProcessBuilder pb = new ProcessBuilder(new String[]{"/bin/bash", "-c", "./test_elanprv2.2.sh > \"$1\"; sleep 1; q", "_", fileName + ".txt"});
System.out.println("wrote text");
pb.directory(dir);
Process start = pb.start();
start.destroy();
}catch (Exception e){
e.printStackTrace();
System.out.println("failed to write text");
}
The process builder does create a txt file but it seems to be empty, and no matter how long I set the sleep to, the programs seems to instanly return the print statement.
It would really be appreciated if anyone could tell me what I am doing wrong.
Thank you in advance!!
As mentioned by #VGR, try using redirectOutput
public static void Linux(String fileName){
try {
File dir = new File("/usr/local/bin");
ProcessBuilder pb = new ProcessBuilder(new String[]{"/bin/bash", "-c", "./test_elanprv2.2.sh");
File output = new File("_", fileName + ".txt");
pb.redirectOutput(output);
System.out.println("wrote text");
pb.directory(dir);
Process start = pb.start();
start.destroy();
} catch (Exception e) {
e.printStackTrace();
System.out.println("failed to write text");
}
Most of your issues are due to a misunderstanding of how processes work. These concepts are not Java concepts; you would have the same issues in any other language.
First, you are destroying your process before it runs, and possibly before it even gets started. This is because pb.start() starts the process, and then you immediately destroy it without giving it a chance to complete.
You shouldn’t need to destroy the process at all. Just let it finish:
Process start = pb.start();
start.waitFor();
All processes have their own standard input and standard output. Again, this is not a Java concept; this has been a fundamental feature in Unix and Windows operating systems for a long time.
Normally, when a process prints information by writing it to its standard output. That is in fact what Java’s System.out.println does. In Unix shells (and in Windows), the > character redirects the standard output of a process to a file; the program still writes to its standard output, without ever knowing that the operating system is sending that output to a destination other than the terminal. Since it’s a fundamental operating system function, Java can do it for you:
ProcessBuilder pb =
new ProcessBuilder("/bin/bash", "-c", "./test_elanprv2.2.sh");
pb.redirectOutput(new File(fileName + ".txt"));
Similarly, when a process wants to take input, it normally does so by reading from its standard input. This is not the same as executing another command. When you do this:
./test_elanprv2.2.sh > "$1"; sleep 1; q
You are not sending q to the shell script. The above commands wait for the shell script to finish, then execute a sleep, then try to execute a program named q (which probably doesn’t exist).
Since the test_elanprv2.2.sh shell script probably accepts commands by reading its standard input, you want to send the q command to the standard input of that process:
ProcessBuilder pb =
new ProcessBuilder("/bin/bash", "-c", "./test_elanprv2.2.sh");
pb.redirectOutput(new File(fileName + ".txt"));
Process start = pb.start();
Thread.sleep(1000);
try (Writer commands = new OutputStreamWriter(start.getOutputStream())) {
commands.write("q\n");
}
// Caution: Call this AFTER writing commands. You don't want to write
// to the standard input of a process that has already finished!
start.waitFor();

Linux kill Java Process from java console application

I'm trying to kill off a already running java process using the Name of the .jar file.
It works completely fine when running the command
pkill -9 -f myapp.jar
from terminal but it doesn't work when you run that same command in a ProcessBuilder.
BufferedReader killStream;
String line;
try{
String[] args = new String[] {"pkill", "-9", "-f", " myapp.jar"};
Process proc = new ProcessBuilder(args).start();
killStream = new BufferedReader(new InputStreamReader(proc.getInputStream()));
line = killStream.readLine();
System.out.println(line);
return true;
}catch(Exception e){
e.printStackTrace();
return false;
}
killStream always return 'null'
What am i doing wrong here?
There are a few missing points here, aside from what is mentioned above regarding the passing in of the arguments your code could do with some more refining.
First of all why not use a try with resources clause to make sure that your resources are managed automatically and get always closed correctly?
With this in mind your code would look like:
try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()))) {
// code to parse the command's output.
} catch (IOException e) {
// code to handle exceptions
}
Secondly, with the current code your method will always return true even if the pkill command has not run correctly.
Ideally would should wait for the process to terminate using Process#waitFor and then invoke Process#exitValue to retrieve the exit status of the command. Then you should return true or false based on whether the exit code is 0 or anything else.
Finally in order to be a bit more efficient, I would suggest using a StringBuilder to collect and append all of the process's output lines and just printing out that String.
Note that there are even better methods to encapsulate all this procedures making it more generic and re-usable while also using Java 8+ API (like streams, consumers etc etc).

Java ProcessBuilder issue

I am having trouble using the > operator to write to file in Process Builder. The actual process will run fine and let me parse using a InputStreamReader etc to parse the output. I want the process to be written to file using command line like >test.json for example.
Here is my code
try {
//process builder used to run a Python script
ProcessBuilder process = new ProcessBuilder("python",
System.getProperty("user.dir")+"\\createJson.py","--structure","cloc.csv",
"--weights","EntityEffort.csv",">","a.json");
process.directory(new File("c:\\users\\chris\\desktop\\test2"));
Process p = process.start();
} catch(Exception e) {
e.printStackTrace();
}
As #JimGarrison points out, > is interpreted by the shell. Here you are directly starting a process for createJson.py, without a shell.
In UNIX you could use ProcessBuilder to start a shell using:
process = new ProcessBuilder("bash", "someCommand", ">", "outputfile");
Something similar will probably work with Windows and cmd.exe.
However, it's not very good practice. It's an opportunity for command injection attacks. Calling external processes is a last-resort approach, and you should try and minimise what you do within those processes.
So you would be better off sticking with what you have, and handle the redirect to file in Java. The ProcessBuilder javadoc gives an example:
File log = new File("log");
processBuilder.redirectOutput(Redirect.appendTo(log));

Execute command from Java

I'm trying to execute a script from Java program:
public class TestCommandLine
{
public static void main (String[] args)
{
String PATH = "/path/programs/";
String command = PATH + "name_programs param1 param2";
executeCommand (command);
}
private static String executeCommand (String command)
{
StringBuffer output = new StringBuffer();
String line = "";
Process p;
try {
p = Runtime.getRuntime ().exec (command);
p.waitFor ();
BufferedReader reader = new BufferedReader (new InputStreamReader (p.getInputStream ()));
while ((line = reader.readLine ()) != null) {
output.append (line + "\n");
}
}
catch (Exception e) {
e.printStackTrace ();
}
return output.toString ();
}
}
there is not error, but the program does not run. I also try others solutions from stackoverflow but all of them didn't work
If you'd given your actual command to start with, this would have been much quicker.
You cannot use Process.exec to run shell-interpreted commands. Instead it executes programs directly. Thus input/output redirection (|, >, etc.) is not possible.
If you actually read the stderr (getErrorStream()) output it would probably be along the lines of "invalid argument: >".
You will either have to:
Redirect the output in Java. Read from the process's stdout (getInputStream()) and write to a FileOutputStream of some kind.
Execute a shell instead of your command directly. For example /bin/sh -c "command arg > file". The quoted section must be passed to sh as a single argument. In this case you wouldn't be able to see anything in stdout, and would have to open and read the file you just wrote to. The first option is probably more sensible.
And as pointed out elsewhere, unless your expecting a very small amount of output, you shouldn't wait for the command to exit before consuming the streams.
The only time I've done it I've used something like this:
Process p = Runtime.getRuntime().exec("foo.exe");
Have you tried that? If so, what was the error you got back?
Your command is producing output that you want to read, but you refuse to read any of it until the command has finished producing it all and has exited (not calling getInputStream() until after waitFor()).
If your command doesn't produce much output, this is OK, Java can buffer it. But if your command produces a lot of output, Java can't buffer it all, and the command gets blocked.
The operating system won't let the command write any more output because Java's buffer is full and you haven't instructed Java to empty it. So the program is blocked, and Java's waitFor() will never come back.
To solve your problem, you should call getInputStream() immediately after getting the Process object back from exec(), and you should create a new Thread that is responsible for reading the command output into your StringBuffer.
You should then waitFor() the process to finish, to see if it exited successfully, and then you can wait for the thread to get to the end of the inputstream and finish - at that point, it is safe to read through the StringBuffer with the full output from your command.

How can i run a .jar file in java

I'm making an update function for my project, it's working great, until i want it to restart, basically I download the new file and replace it with the old one, and then i want to run it again, now for some reason it doesn't wna run, and i don't get any error...
Here is the complete update class:
http://dl.dropbox.com/u/38414202/Update.txt
Here is the method i'm using to run my .jar file:
String currDir = new File("(CoN).jar").getAbsolutePath();
Process runManager = Runtime.getRuntime().exec("java -jar " + currDir);
It's not clear to me, why do you need to run the jar with a call to exec() . Given that you need to run the code in the .jar file from a Java program, you could simply run the main() method as defined in the jar's manifest, and capture its output - wherever that is.
Using exec() is OK when you need to call a program from the underlying operating system, but there are easier ways to do this if both the caller and the callee are Java programs.
Now, if your jar is gonna change dynamically and you need to update your program according to a new jar, there are mechanisms for reloading its contents, for instance take a look ath this other post.
The JavaDocs for the Process class specifically point out that if you don't capture the output stream of the Process and promptly read it that the process could halt. If this is the case, then you wouldn't see the process that you started run.
I think you have to capture the stream like this :
BufferedReader stdInput = new BufferedReader(new InputStreamReader(runManager.getInputStream()),8*1024);
BufferedReader stdError = new BufferedReader(new InputStreamReader(runManager.getErrorStream()));
// read the output from the command
String s = null;
System.out.println("Here is the standard output of the command:\n");
while ((s = stdInput.readLine()) != null) {
System.out.println(s);
}
The exec function doesn't automatically lookup into the PATH to start a process, so you have to pass the complete path for the java binary.
You can do that by using the java.home system property, see this answer: ProcessBuilder - Start another process / JVM - HowTo?
No one here seemed to help me, so I went to ask my friend and I had it almost right. It abiously required the string to be an array.
solution:
String[] cmd = {"java", "-jar", currDir};
try {
Runtime.getRuntime().exec(cmd);
} catch (IOException e1) {
e1.printStackTrace();
}

Categories