在使用Java程序调用视频推流的ffmpeg.exe程序时,遇到视频缓存导致推流中断的情况,特此记录一下这个细节
1.代码原点
Runtime runtime = Runtime.getRuntime();
Process process = runtime.exec("ping 127.0.0.1 -t");
2.pom.xml
<!-- https://mvnrepository.com/artifact/net.java.dev.jna/jna-platform -->
<dependency>
<groupId>net.java.dev.jna</groupId>
<artifactId>jna-platform</artifactId>
<version>4.1.0</version>
</dependency>
3.资源使用的不同
//打开windows窗口,如果启动的是exe程序,则启动的exe将使用windows资源
String cmdStr1 = cmd /k ping 127.0.0.1 -t
//不打开windows窗口,如果启动的是exe,则exe所消耗的是JAVA虚拟机的资源
String cmdStr2 = ping 127.0.0.1 -t
4.进程销毁
//销毁JAVA虚拟机中的进程
process.destroy();
//销毁windows操作系统的进程,通过PID
private static void killProcessTree(Process process){
try {
Field f =process.getClass().getDeclaredField("handle");
f.setAccessible(true);
long handl =f.getLong(process);
Kernel32 kernel = Kernel32.INSTANCE;
WinNT.HANDLE handle = new WinNT.HANDLE();
handle.setPointer(Pointer.createConstant(handl));
int ret =kernel.GetProcessId(handle);
Long PID =Long.valueOf(ret);
String cmd =getKillProcessTreeCmd(PID);
Runtime rt =Runtime.getRuntime();
Process killPrcess = rt.exec(cmd);
killPrcess.waitFor();
killPrcess.destroy();
}catch(Exception e) {
e.printStackTrace();
LOG.info(e.getMessage());
}
}
private static String getKillProcessTreeCmd(Long Pid)
{
String result = "";
if(Pid !=null)
result ="cmd.exe /c taskkill /PID "+Pid+" /F /T ";
return result;
}