启动独立进程
使用Java在Linux中启动独立的任务进程,即使停掉Java后台,此任务也不会被停止掉
需要注意的是,此方法需要将命令写入shell文件,用启动sh文件的方式进行
//检查进程状态
boolean ffmpegStatus = iHlCameraInfoService.ffmpegStatus(startffmpegfileName);
//执行进程启动
if (ffmpegStatus){
iHlCameraInfoService.ffmpegCommand(id,type,websocketPort,port,dpi);
ProcessBuilder processBuilderFFmpeg = new ProcessBuilder("nohup","sh",startffmpegfileName).inheritIO();
try {
processBuilderFFmpeg.start();
}catch (Exception ioe){}
System.out.println("ffmpeg未启动");
}
//通过命令行方式检查ffmpeg状态
public boolean ffmpegStatus(String command) {
boolean flag = true;
BufferedReader reader = null;
try {
//显示所有进程
Process process = Runtime.getRuntime().exec("ps -ef");
reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line = null;
while ((line = reader.readLine()) != null) {
if (line.contains(command)) {
return false;
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
}
}
}
return flag;
}
//组装启动ffmpeg命令(地面枪机)
public void ffmpegCommand(String id, String type, String websocketport, String cameraPort, String dpi) {
//组装命令
String ffmpegCommand;
String fileName;
//0为无人机吊舱,1为地面枪机,2为地面球机
if (type.equals("0")) {
ffmpegCommand = "ffmpeg -i \"tcp://0.0.0.0:" + cameraPort + "?listen\" -q 0 -f mpegts -codec:v mpeg1video -s " + dpi + " http://127.0.0.1:" + websocketport + "/hl/123";
fileName = "/opt/jsmpeg/start/startffmpeg" + id + ".sh";
} else {
ffmpegCommand = "ffmpeg -rtsp_transport tcp -i \"rtsp://admin:hl12345678@127.0.0.1:" + cameraPort + "/h264/ch1/main/av_stream\" -q 0 -f mpegts -codec:v mpeg1video -s " + dpi + " http://127.0.0.1:" + websocketport + "/hl/123";
fileName = "/opt/jsmpeg/start/startffmpeg" + id + ".sh";
}
//写入文件
makeFile(ffmpegCommand, fileName);
}
void makeFile(String command, String fileName) {
try (FileOutputStream fos = new FileOutputStream(fileName);
OutputStreamWriter osw = new OutputStreamWriter(fos);
BufferedWriter bw = new BufferedWriter(osw);) {
bw.write(command);
bw.flush();
} catch (Exception e) {
}
}