gpt4 book ai didi

node.js - 在 NodeJs 中杀死由 spawn 触发的 FFmpeg 进程

转载 作者:太空宇宙 更新时间:2023-11-03 23:17:40 27 4
gpt4 key购买 nike

我面临一个问题,想要杀死 FFmpeg进程由 spawn 触发来自child_process native NodeJs包。

这是我用来触发 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进程正在运行。

root 198 1 0 09:26 ? 00:00:00 ffmpeg -i /path/to/input -ss 00:01:47 -vframes 1 /path/to/output

root 217 1 0 09:26 ? 00:00:00 ps -ef

您知道如何正确终止 ffmpeg 进程吗?

最佳答案

node.js documentation 中所述subprocess.kill([signal]) 中,默认发送的信号为 SIGTERM

Ffmpeg 不会终止接收 SIGTERM,正如 @sashoalm 在 here 中所解释的那样.

Newer versions of ffmpeg don't use 'q' anymore, at least on Ubuntu Oneiric, instead they say to press Ctrl+C to stop them. So with a newer version you can simply use 'killall -INT' to send them SIGINT instead of SIGTERM, and they should exit cleanly.

<小时/>

所以调用x.kill('SIGINT');

关于node.js - 在 NodeJs 中杀死由 spawn 触发的 FFmpeg 进程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53428263/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com