【发布时间】:2019-04-24 23:29:09
【问题描述】:
我正面临一个问题,我想从 child_process 本机 NodeJs 包中终止由 spawn 触发的 FFmpeg 进程。
这是我用来触发 ffmpeg 进程的脚本。
假设转换需要很长时间,比如大约 2 小时。
/**
* Execute a command line cmd
* with the arguments in options given as an array of string
* processStore is an array that will store the process during its execution
* and remove it at the end of the command or when error occurs
*/
function execCommandLine({
cmd,
options = [],
processStore = [],
}) {
return new Promise((resolve, reject) => {
const spwaned_process = childProcess.spawn(cmd, options);
// Append the process to a buffer to keep track on it
processStore.push(spwaned_process);
// Do nothing about stdout
spwaned_process.stdout.on('data', () => true);
// Do nothing about stderr
spwaned_process.stderr.on('data', () => true);
spwaned_process.on('close', () => {
const index = processStore.indexOf(spwaned_process);
if (index !== -1) {
processStore.splice(index, 1);
}
resolve();
});
spwaned_process.on('error', () => {
const index = processStore.indexOf(spwaned_process);
if (index !== -1) {
processStore.splice(index, 1);
}
reject();
});
});
}
const processStore = [];
await execCommandLine({
cmd: 'ffmpeg',
options: [
'-i',
'/path/to/input',
'-c:v',
'libvpx-vp9',
'-strict',
'-2',
'-crf',
'30',
'-b:v',
'0',
'-vf',
'scale=1920:1080',
'/path/to/output',
],
processStore,
});
在转换过程中,会调用以下代码来杀死所有进入processStore的进程,包括被触发的FFmpeg进程。
// getProcessStore() returns the const processStore array of the above script
getProcessStore().forEach(x => x.kill());
process.exit();
程序退出后,当我运行ps -ef | grep ffmpeg时,还有一些FFmpeg进程在运行。
根 198 1 0 09:26 ? 00:00:00 ffmpeg -i /path/to/input -ss 00:01:47 -vframes 1 /path/to/output
根 217 1 0 09:26 ? 00:00:00 ps -ef
你知道正确杀死 ffmpeg 进程的方法吗?
【问题讨论】:
标签: node.js ffmpeg spawn kill-process