Java – How to Terminate a Process Normally Created using ProcessBuilder

ffmpeg, java, kill-process, processbuilder, windows

I am creating Processes using ProcessBuilder in my Java Application. The created process executes some FFMPEG commands which actually copy the RTSP streams in specified destination media file.

ProcessBuilder builder = new ProcessBuilder("ffmpeg", "-i", RTSP_URL, "-f", fileFormat, destFilePath);Process processToExecute = builder.start();

I want to close the process before it completes its execution. So, If I run this FFMPEG command directly in windows CMD and then press 'CTRL+C' after 5 seconds then process get terminates with status '2'. And I can play the media file created so far.

So, If I do the same operation in my Java Application using:

 process.destroy(); //I call this method after 5 sec

I get the status code '1' which means abnormal termination. I get the status by the following way:

 processToExecute.destroy(); processToExecute.exitValue(); //This return me status '1'

And I can't play the media file and I think this is due to the abnormal termination of the process.

So how I can terminate the process created using ProcessBuilder in the same way we do in CMD with (CTRL+C) so that I may play the created media file ?

I want to terminate process (created using ProcessBuilder) in Java Application with status code of '2' that I get when I terminate process using CMD.

Java – How to Terminate a Process Normally Created using ProcessBuilder

So, when I try to delete that file once app terminates, I get the following error:

The Action Can't be Performed Because File is Opened in FFMPEG.exe

Which means that process is not terminating the command it is executing. That command still has occupied this file that's why I am not getting able to play it. Process gets terminate when I call:


But, the task it is performing (that is execution of a command) is still active. Strange!!!!

Java – How to Terminate a Process Normally Created using ProcessBuilder

Actually If I directly press 'CTRL+C' or 'q' in cmd when process is running then it terminates the process successfully and this process is no more visible in the currently executing processes lists.

And Programatically when I call method:

cmd> processToExecute.destroy();

It terminates the process but when I see the list of currently executing processes I can still see them over there.

And same scenario exists If I try to terminate this process using 'taskkill' or 'kill' command in another CMD by specifying their's name or pid that still process terminates abnormally.

P.S. I use the following command to see the running processes:


So from this it proves that destroy() method from Application and 'taskkill or kill' command from another CMD is not terminating the process normally that pressing 'CTRL+C' and 'q' does.

Best Solution

Maybe try...


Or you could try to write to the stdin of the process...