I have 4 lines in my bat file, but my thread goes on before the cmd closes.
Here's my code:
rt = Runtime.getRuntime();
proc = rt.exec("cmd /c start C:\\temp\\test.bat");
if(proc.waitFor() == 0) {
return "did it";
} else {
return "nooope";
}
I always get the did it before cmd closes.
Here is my batch-file:
#ECHO off
taskkill /IM "Process.exe" /F
cd "C:\Program Files\ProcessFolder"
START /WAIT Process.exe
START otherProcess.exe
EXIT
any help?
The problem is that you're using start - which will start a new shell in which to run the batch file. The original shell then closes, so the process terminates, and your Java program continues.
Remove the start and it should work, in terms of waiting for the batch file to end. However, you've then got the same problem again within the batch file when you start otherProcess.
Either don't use start, or always use start /wait within the batch file.
If you use start /wait within the Java code, however, you'll end up with a command prompt sitting there at the end of the batch file execution, as far as I can tell by experimentation.
Related
I'm starting a process (.bat) in java using java.lang.Process
Runtime.getRuntime().exec("cmd /c start /wait test.bat");
exitCode = process.waitFor();
The .bat process inturn calls .exe file, this .exe returns an exit code !=0 on error cases.
START /W test.exe
EXIT %ERRORLEVEL%
I want to get back the exit code returned from the batch file, but still I get back exitcode=0 always. I referred this but does not help.
Please let me know how can I get back the actual returned exit code from the process.
You are asking Java to launch CMD.EXE with the command start /wait test.bat which starts a second CMD.EXE process. There is EXIT %ERRORLEVEL% in the second CMD.EXE but there is no call in the scriptlet which tells the first CMD.EXE to use the status code as EXIT %ERRORLEVEL%. Thus you don't get the non-zero code of test.bat passed up to first CMD.EXE.
The fix is easy as you don't need to use start /wait, just change the command to avoid second CMD.EXE process and then the EXIT %ERRORLEVEL% of the batch script applies to the only CMD.EXE:
Process process = Runtime.getRuntime().exec("cmd /c test.bat");
Note that Runtime is not a good way to launch sub-processes, use ProcessBuilder instead with cmd passed as String[] not String so that you don't need to escape spaces in parameters.
Heed the warnings of the Process javadoc: failure
to promptly write the input stream or read the output stream of
the process may cause the process to block, or even deadlock. This means you should consume STDERR + STDOUT on different threads, or redirect STDERR to STDOUT, or redirect them to files or inherit IO streams - otherwise you may encounter problems. Many examples shown in StackOverflow won't work correctly.
I run process from my Java code like this p = run.exec("cmd /c start \"\" C:\\<nameof .cmd file>");. At some point, I want to kill this process. Calling destroy() method on process kill the process, but I want to turn off command line, where procces is still running. When I looked to Task Manager, this process has no name, it has only postfix .exe.
In Task Manager, it look like this:
So I cannot do this p = run.exec("taskkill /F /IM <nameofexe>.exe");, because this running process dont have name.
Is there a way, how to completely turn off cmd and kill this running process?
When you launched your process, the CMD call may have launched additional child processes. Odds are good your second command line is killing one of the children, but not the CMD itself. The ideal situation would be to kill the launched process, not to run a second command line executable to kill (possibly) one of the children.
Process child = run.exec("cmd /c start \"\" C:\\<nameof .cmd file>");
if (timeToKillTheProcess) {
child.destroy();
child.waitFor();
}
I am running a batch (ScanProject.bat) file using java by following code
Process p= Runtime.getRuntime().exec("cmd /c start /wait ScanProject.bat "+ BaseProjDir+"\\"+jo.getString("Name")+" "+st.nextToken());
System.out.println("Exit value : "+p.waitFor());
And following is the batch file code :-
%2:
cd %1
ant -f ..\antbuild.xml analyse
exit
Batch file run successfully but problem is command prompt window do not closes automatically and hence Process do not terminated automatically and my program wait for infinite time to complete this process.Please suggest me any technique so that cmd exit after running ant -f ..\antbuild.xml analyse command.
Thanks.
cd /D "Full path of directory" or pushd "Full path of directory" with popd before exit is better to switch the current directory to any directory on any drive (cd and pushd/popd) or even to a network share (just pushd/popd). Run in a command prompt window cd /? and pushd /? for details.
cmd /C starts a new Windows command process with closing the process automatically after last command was executed. Run in a command prompt window cmd /? for details on options of Windows command interpreter.
start is a command to start a new Windows command process or a GUI/hybrid application in a separate process.
So what you do here is starting a new Windows command process which starts a new Windows command process.
Running in a command prompt window start /? outputs the help for this command. start interprets often the first double quoted string as title string for the new command process. This causes often troubles on command lines with at least 1 double quoted string. Therefore usage of start requires often an explicit definition of a title string in double quotes as first argument for start which can be even an empty string, i.e. simply "" as first argument after start.
As it can be read after running exit /? in a command prompt window, this command without /B always exits the current Windows command process immediately. So when ant.exe finished, the command process in which the batch file was processed is definitely terminated.
I'm having no experience on Java development, but in my point of view it should be enough to use the following execution command which does not need a batch file at all.
The Java code line
Process p= Runtime.getRuntime().exec("cmd.exe /C cd /D \"" + jo.getString("Name") + "\" && ant.exe -f ..\\antbuild.xml analyse");
should be enough to
start a new Windows command process,
set the current directory within this command process to the drive and directory specified by jo.getString("Name") which of course must return a directory path with drive letter and using backslashes as directory separators, and on success
execute ant in this directory with the specified parameters
with terminating the Windows command process automatically after console application ant.exe finished if ant.exe is a console application.
I'm not sure if cmd.exe /C is needed at all.
I suggest to test this command first manually from within a command prompt window. Then use it in the Java application if really working and producing the expected result. And finally I would further test if cmd.exe /C is needed at all in Java code.
See Single line with multiple commands using Windows batch file for details about the operator && to run a command after previous command was successful. And see also Why do not all started applications save the wanted information in the text files as expected? for an explanation of console / GUI / hybrid application.
NOTE: There is also Java Runtime method exec(String[] cmdarray, String[] envp, File dir) to execute a command like ant.exe with its parameters -f and ..\antbuild.xml and analyse in the directory defined with third parameter which might be better for this task.
Swap out exit for taskkill, assuming you do not have any other cmd processes running. Not very graceful but it will get the job done.
%2:
cd %1
ant -f ..\antbuild.xml analyse
taskkill /im cmd.exe
I was able to use an amalgamation of SO questions to get a line of code that would:
Run a batch file from within a Java application
Include an argument located in the same directory as the batch file
The argument & batch file are in a directory unrelated to the JAR/java app
So I used this:
Runtime.getRuntime().exec("cmd /c start batchfile.bat argument.js", null, new File( path ));
This works well except that it leaves the cmd prompt open after it has finished executing the batch file. I've looked around and it seems like having the /c flag should make it close after running, but for me it has been staying open. I tried removing 'start' but this meant that the cmd prompt never opened up at all.
Is it because I'm combining having an argument and using a different path that it's not causing the cmd prompt to open and then close after completion like most examples on SO?
Calling both cmd.exe and start in that order is creating a separate window but it doesn't seem like the command shell is terminating based on what you described. I was able to replicate this behavior in a simple batch script. If you want to leave your Java call as it is, check to make sure your batch script includes an exit statement. Preferably exit based on a success or failure condition within your batch script (i.e.: exit 0 or exit 1, etc...)
:: batchfile.bat
...
exit 0
Assuming you are not firing up any new shells within your batch script or prompting for input, adding an explicit exit to your existing batch script should cause the window to close. You can also try to leave your batch script as is, and as others have suggested in comments, change the order of your command text slightly.
Use this instead
start cmd.exe /c ...
Where you call start first and then call cmd.exe /c after followed by your parameters as needed. I tried both options here and either worked fine to cause the batch window to close as expected.
Pass the below command to Runtime to execute.
taskkill /F /IM (processName)
Runtime.getRuntime().exec("taskkill /F /IM "+pProcessName);
I want to create auto-updater of my program.
In java part it looks like
int pid = Kernel32.INSTANCE.GetCurrentProcessId();
String cmd = folder + "update.bat" + " " + currentLoc + " " + updateLoc + " " + Integer.toString(pid);
Runtime.getRuntime().exec(cmd);
And the batch contains
SET "name=GameDrive Logs Viewer.exe"
SET "myname=update.bat"
TASKKILL /pid %3
TASKKILL /pid %3
DEL "%1\%name%"
MOVE "%2\%name%" "%1"
"%1\%name%"
DEL "%2\%myname%"
So, I'm killing current program and delete it.
Then i move new version to old folder, run new version, and delete the bat file.
This bat file is perfectly works when i call it from cmd with sending parameters.
But nothing is happend when i'm trying use it from java program.
As i found, that all Dialog windows creating from current program have the same processID. (I tested it from another bat).
So, my guess is the batch which is called from my java program get the same processID and kill himself.
Am I right? And if yes - can how I do that?
I guess you need launch your update.bat in another cmd instance as follows (add path as necessary). In JAVA use updatecall.bat with next content:
Either with CMD.exe: Start a new CMD shell and (optionally) run a command/executable program.
cmd /C ""update.bat" %*"
or with START: Start a program, command or batch script (opens in a new window.)
start "" "update.bat" %*
If started a batch file then the command processor is run with the /K switch to cmd.exe. This means that the window will tend to remain after the batch has been run. To auto close it, add EXIT command to the end of started batch.
I'm sure there is a smarter solution without any auxiliary batch...