How do I abort execution after encountering error? - java

At the moment I use a simple cmd start command. So:
start ../myexe.exe parameters
As you can see this exe is created from a cpp solution.
When an error occurres I get a pop up like this:
But I actually want this to abort automatically, because it should run in the background totally. Is there a way to run an exe like this? Should I change something in the cpp solution? Or should I write some kind of script to abort the execution?
Another spin of the problem is, that I need to run the exe in a java project. Should I change something here? The implementation so far:
Process process = Runtime.getRuntime().exec("cmd /c start /B /wait "
+ BASE_PATH
+ "/ciff_caff_parser.exe "
+ caffFullPath + " "
+ caffId
+ " || exit /b");
logger.info("Waiting for parser to finish...");
int i = process.waitFor();
logger.info("Parser finished successfully, with error code: " + i);

Related

How to make a process wait

I have a code that execute an external program. And now I need that my application wait the end of the execution of that external program.
But I'm not shure how I supposed to do that. I tried some things but don't work.
public Image acquireImage() throws IOException, InterruptedException {
process = Runtime.getRuntime().exec("cmd.exe /c start "+ApplicationProperties.getPath()
+ "\\.wimdesktop\\Release\\Static_GenerateGain.exe");
process.waitFor();
System.out.println("EXIT: " + process.exitValue());
return copyImage();
}
The problem is that the System.out.println("EXIT: " + process.exitValue()); print 0 but the external program still running.
You are running cmd.exe and asking it to start a process in the background. So all you are seeing is cmd.exe exit status 0 after it launches your app - and that app may still be running.
If you want waitFor to apply to the sub-process just run the exe directly without the launch wrapper:
process = Runtime.getRuntime().exec(ApplicationProperties.getPath()
+ "\\.wimdesktop\\Release\\Static_GenerateGain.exe");
Note that if your EXE depends on environment variables set by CMD.EXE then you may need to try your original command without "start" for background process:
process = Runtime.getRuntime().exec("cmd.exe /c "+ApplicationProperties.getPath()
+ "\\.wimdesktop\\Release\\Static_GenerateGain.exe");
In both cases above you may run into second issue that the command freezes, this is because you are not reading the Stdout and error streams. There are many SO posts on how to do this.

how to execute a command with it's native gui using process builder

if(os.contains("windows"))
{
File bat = new File(System.getenv("APPDATA") + "/SelfCommandPrompt", appId + "-run.bat");
bat.getParentFile().mkdirs();
List<String> list = new ArrayList(1);
list.add("#echo off");
list.add("start" + " \"" + appName + "\" " + command);
IOUtils.saveFileLines(list, bat, true);
ProcessBuilder pb = new ProcessBuilder(bat.getAbsolutePath());
//inherit IO and main directory
pb.directory(getProgramDir());
//fire the batch file
pb.start();
System.exit(0);
}
So I dynamically create a .bat file and I want to run the process but, NOT IN THE BACKGROUND. Java forces the process to happen in the background how do I make it so it's not in the background? I am not looking to get the output stream from the .bat file I only want to execute it with the native gui it's intended to use on double click. Everywhere I look on these forums it only tells me how to do it in the background and get the outputstream? Why isn't there a boolean for this in the process builder? For my program specifically right now I want to reboot my java program with command prompt terminal on double click. I have the command generation working I tested the .bat file but, java again forces it to happen in the background.
Another use for doing a process not in the background. A java launcher for a game which executes a program with the gui not in the background which I may also need in the future.
Also the bat files output which is dynamically generated based off of the enviorment
java -Dfile.encoding=Cp1252 -cp C:\Users\jredfox\Documents\MDK\md5-spreadsheet\filededuper\bin;C:\Users\jredfox\Documents\MDK\md5-spreadsheet\filededuper\libs\apache-codecs.jar jredfox.selfcmd.SelfCommandPrompt true jredfox.filededuper.Main
edit I figured out a command for windows but, only windows. I need commands for mac
Runtime.getRuntime().exec("cmd /c start" + " \"" + appName + "\" " + command);
Figured it out.
basically get the terminal string on linux you need to make an api for it
save any shell scripts you need in the appdata
make an api to get the app data folder
create your custom command
return if conditions are not met like the System.console != null for my thing yours will be different.
execute command in new terminal window therefore the new native terminal using os commands.
All the code is found here.
https://github.com/jredfox/OpenTerminal

Issue starting cmd.exe twice in a row

I am trying to automate some processes that were build in ancient times, for the sake of avoiding repetitive actions. It is required that the processes are started with one batch and stopped with another (this can not be changed btw).
So i made a commandline tool to do this (and many other repetitive stuff) and I have modelled a command that starts the 'startbatch' and a command that start the 'stopbatch'. Both commands work fine separatly (as I tested them separatly) but there seems to be a problem when i want execute them one after another (in the correct order ofcourse). I get the following error in new cmd.exe window:
The process cannot access the file because it is being used by another process.
the code that i am using to start the batches looks like this:
public void startBatchInDev(String company){
String startBatchFolder = locations.getLocationFor("startbatch");
try{
Runtime runtime = Runtime.getRuntime();
runtime.exec("cmd.exe /C cd \"" + startBatchFolder + "\" & start cmd.exe /k \"" + BATCHSTART + company.toLowerCase()+ "-dev" + BATCH_SUFFIX + "\"");
}
catch(IOException ioe){
ioe.printStackTrace();
}
}
public void stopBatchInDev(String company){
String startBatchFolder = locations.getLocationFor("startbatch");
try{
Runtime runtime = Runtime.getRuntime();
runtime.exec("cmd.exe /C cd \"" + startBatchFolder + "\" & start cmd.exe /k \"" + BATCHSTOP + company.toLowerCase()+ "-dev" + BATCH_SUFFIX + "\"");
}
catch(IOException ioe){
ioe.printStackTrace();
}
}
The names of the batchfiles are concatenated, but they are OK once the application is running.
The error message is quite clear, some file is locked and I can't access it because of it. Some googling confirms my suspicion, but I can't seem to find a solution for this. The hits in google are all about obvious uses of files, like an obvious shared resource. But in my case, i am not working on the same batch file. The stop and start batch are two different files. So I am actually starting to think that it might be the cmd.exe file that is being locked by windows...
So this question is actually two questions:
- what is the exact cause of the described problem?
- how do i programmatically fix this (if possible)?
thanks in advance!
So, basically, bat is not so great :-(
I was able to repro this from java, but I also found that this script:
#echo off
echo STOP
echo STOP >> E:\tmp\java\logfile.txt
C:\cygwin\bin\sleep.exe 1
echo STOP1 >> E:\tmp\java\logfile.txt
C:\cygwin\bin\sleep.exe 1
echo STOP2 >> E:\tmp\java\logfile.txt
When run twice like this:
start test.bat && start test.bat
Will fail with one or more messages like:
The process cannot access the file because it is being used by another process.
The reason is that " >> " redirection opens the file for Read/Write access but only FILE_SHARE_READ sharing. If two different programs attempt to open the file this way, one of them fails.
So, you cannot have two different batch files running at the same time and logging to the same file

Run bat file in Java and wait

You would think that launching a bat file from Java would be an easy task but no... I have a bat file that does some sql commands for a loop of values read from a text file. It is more or less like this:
FOR /F %%x in (%CD%\listOfThings.txt) do sqlcmd -Slocalhost\MSSQL %1 %2 -d %3 -i %CD%\SQLScripts\\%%x
exit
Don't worry about the specifics they are not important. What i want is to simply run this bat file from within Java and have it wait until execution is finished. Apparently it is not easy. What i have so far is this:
Runtime.getRuntime().exec("cmd /K start SQLScriptsToRun.bat"
+" -U"+getUser()
+" -P"+getPass()
+" " + projectName);
return true;
The problem is that the exec() method returns immediately. The bat file runs for a good 2-3 minutes. I tried removing the start but to no avail. I tried many variations but it got me nowhere. Any ideas on how to do this simple task?
You should not ignore the return value of .exec(). It gives you a Process object that you can waitFor(), like this:
final Process process = Runtime.getRuntime().exec("blahblahblah");
final int exitVal = process.waitFor();
// if exitVal == 0, the command succeeded
you need to use waitFor on the process exec call returns.

cause the main process wait until another process is finished

I have a synchronization problem in java.
I want my main thread to wait until process "p1" is finished.
I have used "waitfor" method. it has not worked for me.
Process p1 = runtime.exec("cmd /c start /MIN " + path + "aBatchFile.bat" );
p1.waitFor();
Could anybody help me please?
Thank you so much.
The problem here is that the Process object you get back from exec() represents the instance of cmd.exe that you start. Your instance of cmd.exe does one thing: it starts a batch file and then exits (without waiting for the batch file, because that's what the start command does). At that point, your waitFor() returns.
To avoid this problem, you should be able to run the batch file directly:
Process p1 = runtime.exec(path + "aBatchFile.bat");
p1.waitFor();
Alternately, try the /wait command line option:
Process p1 = runtime.exec("cmd /c start /wait /MIN " + path + "aBatchFile.bat" );
p1.waitFor();

Categories