1、terminal 执行正常的ffmpeg同一条命令行语句,Java 调用报错no such file or directory。
既然 terminal 可以成功执行,启动 shell,然后自定义命令行作为参数传递给 shell 解释器。shell 知道如何将程序员的意图转达给底层。使用 sh -c,将自定义 CMD 行作为其参数,最后使用 java.lang.Runtimeexec(String[] cmdarray):
Runtime.getRuntime().exec(new String[]{“sh”,"-c",command})
2、获取转码进程跟杀死转码进程。
mport com.sun.jna.Platform;
import com.sun.jna.examples.win32.Kernel32;
import com.sun.jna.examples.win32.W32API;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.Field;
@Slf4j
public class ProcessLinuxUtil {
public static String getProcessId(Process process) {
long pid = -1;
Field field = null;
if (Platform.isWindows()) {
try {
field = process.getClass().getDeclaredField("handle");
field.setAccessible(true);
pid = Kernel32.INSTANCE.GetProcessId((W32API.HANDLE) field.get(process));
} catch (Exception ex) {
ex.printStackTrace();
}
} else if (Platform.isLinux()) {
try {
Class<?> clazz = Class.forName("java.lang.UNIXProcess");
field = clazz.getDeclaredField("pid");
field.setAccessible(true);
pid = (Integer) field.get(process);
} catch (Throwable e) {
e.printStackTrace();
}
}
log.info("-------------pid:"+pid);
return String.valueOf(pid);
}
/**
* 关闭Linux进程
*
* @param pid 进程的PID
*/
public static boolean killProcessByPid(String pid) {
if (StringUtils.isEmpty(pid) || "-1".equals(pid)) {
throw new RuntimeException("Pid ==" + pid);
}
Process process = null;
BufferedReader reader = null;
String command = "";
boolean result = false;
if (Platform.isWindows()) {
command = "cmd.exe /c taskkill /PID " + pid + " /F /T ";
} else if (Platform.isLinux()) {
command = "kill -9 " + pid;
}
try {
//杀掉进程
process = Runtime.getRuntime().exec(command);
reader = new BufferedReader(new InputStreamReader(process.getInputStream(), "utf-8"));
String line = null;
while ((line = reader.readLine()) != null) {
log.info("kill PID return info -----> " + line);
}
result = true;
} catch (Exception e) {
log.info("杀进程出错:", e);
result = false;
} finally {
if (process != null) {
process.destroy();
}
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
}
}
}
return result;
}
}