Trying to use wait() in java Process Builder - java

Using process builder in java but I want the program to wait while the process is finished.
I tried to use pb.wait() but it keeps on waiting. How do I wait till all the commands have finished executing?
This is a very small part of my code.
String[] commands = {All my commands go here};
String command = "cmd.exe /c " + String.join(" && ", commands);
ProcessBuilder pb = new ProcessBuilder(command.split(" "));
pb.inheritIO();
try {
pb.start();
try {
pb.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
} catch (IOException e) {
System.out.println("Error, Could not run.");
e.printStackTrace();
}
}

The wait() method you called does not do what you expect (check javadoc for more details: https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/lang/Object.html#wait(long))
You want to wait for the process you started:
Process p = pb.start();
p.waitFor();
see https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/lang/Process.html#waitFor()

Related

JNA .FindWindow with regex

Hello I'm working on a program which uses JNA 4.5.1.
I need to know whether a specific program is running or not.
Here is my problem:
hwnd = User32.INSTANCE.FindWindow
(null, "Session Dev/Prod - [32 x 80]");
if (hwnd == null) {
System.out.println("Session Dev/Prod is not running");
Process p = null;
try {
p = Runtime.getRuntime()
.exec("rundll32
url.dll,FileProtocolHandler C:
/ProgramData/Microsoft/Windows/Start
Menu/Programs/IBM Personal
Communications/TNHost");
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
p.waitFor();
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
else{
System.out.println("Host Already open");
User32.INSTANCE.ShowWindow(hwnd, User32.SW_MAXIMIZE );
User32.INSTANCE.SetForegroundWindow(hwnd);
}
The Problem is that the Window-Title changes depending on the monitor size.
hwnd = User32.INSTANCE.FindWindow(null, "Session Dev/Prod - [32 x 80]");
The title is always "Session Dev/Prod" + the size which changes.
I need to find the window which starts with "Session Dev/Prod".
Does anyone know how to do this. Or is there an other way to find out whether a program is running or not? I've tried to do it with Regex as parameter but the function accepts just a String.
Thank you
I had the task once to check whether a program was running or not (and if so kill it) and solved it like this:
public static void isProcessRunning(String processName) throws IOException, InterruptedException {
ProcessBuilder processBuilder = new ProcessBuilder("tasklist.exe");
Process process = processBuilder.start();
// handle errors: process.getErrorStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
if (line.startsWith(processName)) {
System.out.println("Yes program is running");
break;
}
// else {
// System.out.println("No program is not running");
// }
}
}
To find out the name of your task call tasklist in the commandline and look for the name. If it is really 'Session Dev/Prod - [32 x 80]' then you can use 'Session Dev/Prod' as a string...
But note that this is a windows solution. For linux you have to use something like ps -ef

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!

Running an Executable Program from button in Java

The code compiles OK, but when I press the button, nothing happens, would you know why? I want to call the EXIF software when I press my EXIF
EXIF.addActionListener (new ActionListener(){
public void actionPerformed (ActionEvent e) {
try {
Runtime.getRuntime().exec("C:\\Program Files (x86)\\Exif Pilot\\ExifPilot.exe");
} catch(Exception exc) {
/*handle exception*/
}
}
});
The problem is with the executed process output/input streams. When you execute a new process with java it allocates only 8KB for its input stream so you must consume it. Search for process gobblers
Also with windows use cmd /c to execute the program or better:
String[] cmd = {"CMD", "/C", "C:\\Program Files (x86)\\Exif Pilot\\ExifPilot.exe"};
ProcessBuilder processBuilder = new ProcessBuilder(command);
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
while ((String line = br.readLine()) != null) {
System.out.println(line);
}
try {
int exitValue = process.waitFor();
//TODO - do something with the exit value
} catch (InterruptedException e) {
e.printStackTrace();
}

Android Ping command dies on unreachable server

I have been trying to attempt to insert a ping command thread into my Android application, and when the server is reachable the code works great. When the server is unreachable, the process hangs and I have no idea why.
This code works in the emulator, whether the host is resolvable or not, however on an actual device, the process.waitFor never returns, and no output is published from the input or output streams.
Any ideas?
protected double executePing(String ipAddress) {
List<String> commands = new ArrayList<String>();
commands.add("/system/bin/ping");
commands.add("-c");
commands.add("5");
commands.add("-w");
commands.add("5");
commands.add("128.128.128.128");
try {
this.doCommand(commands);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return laten;
}
private void doCommand(List<String> command) throws IOException{
ProcessBuilder pb = new ProcessBuilder(command);
Process process = pb.start();
// any error message?
StreamGobbler errorGobbler = new StreamGobbler(
process.getErrorStream(), "ERROR");
// any output?
OutputStreamGobbler outputGobbler = new OutputStreamGobbler(
process.getInputStream(), "OUTPUT");
// kick them off
errorGobbler.start();
outputGobbler.start();
// read the output from the command
try {
exitVal = process.waitFor();
//Sleep for 10 secs to try to clear the buffer
Thread.sleep(6000);
//pingVal = echo.toString();
if(exitVal == 0 && !pingVal.isEmpty()){
//System.out.println("PING STATS: "+pingVal);
try{
pingVal = pingVal.substring(pingVal.lastIndexOf("rtt min/avg/max/mdev"));
pingVal = pingVal.substring(23);
pingVal = pingVal.substring(pingVal.indexOf("/")+1);
laten = Double.parseDouble(pingVal.substring(0,pingVal.indexOf("/")));
}catch (IndexOutOfBoundsException ex){
System.out.println("PING VAL: "+ pingVal);
ex.printStackTrace();
}
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("ExitValue: " + exitVal);
}
One option would be to create a new thread to ping, and keep it open for a certain amount of time (call it a timeout). If you don't get the desired response, within the desired time, you can close the thread & try again; or, kill the process. This would give you the ability to check for specific response codes, along with the timeout.

Java: wait for exec process till it exits

I am running a java program in Windows that collects log from Windows events. A .csv file is created on which certain operations are to be performed.
The commands are execed and piped. How can I cause my Java program to wait until the process is finished?
Here is the code snippet I am using:
Runtime commandPrompt = Runtime.getRuntime();
try {
Process powershell = commandPrompt.exec("powershell -Command \"get-winevent -FilterHashTable #{ logname = 'Microsoft-Windows-PrintService/Operational';StartTime = '"+givenDate+" 12:00:01 AM'; EndTime = '"+beforeDay+" 23:59:59 '; ID = 307 ;} | ConvertTo-csv| Out-file "+ file +"\"");
//I have tried waitFor() here but that does not seem to work, required command is executed but is still blocked
} catch (IOException e) { }
// Remaining code should get executed only after above is completed.
You need to use waitFor() instead of wait(). That way your thread will block until the executed command finishes.
I found the answer here Run shell script from Java Synchronously
public static void executeScript(String script) {
try {
ProcessBuilder pb = new ProcessBuilder(script);
Process p = pb.start(); // Start the process.
p.waitFor(); // Wait for the process to finish.
System.out.println("Script executed successfully");
} catch (Exception e) {
e.printStackTrace();
}
}
This shall work. If not, specify WHAT exactly does not work
Runtime commandPrompt = Runtime.getRuntime();
try {
Process powershell = commandPrompt.exec("powershell -Command \"get-winevent -FilterHashTable #{ logname = 'Microsoft-Windows-PrintService/Operational';StartTime = '"+givenDate+" 12:00:01 AM'; EndTime = '"+beforeDay+" 23:59:59 '; ID = 307 ;} | ConvertTo-csv| Out-file "+ file +"\"");
powershell.waitFor();
} catch (IOException e) { }
// remaining code

Categories

Resources