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

标签 node.js ffmpeg spawn kill-process

我面临一个问题,想要杀死 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/

相关文章:

javascript - 等待直到满足条件 Selenium-Webdriver

PowerShell 生成一个后台进程以保持事件状态

arrays - swift 中的 "Attemped to add a SKNode which already has a parent"

ffmpeg - 使用 FFMPEG 添加启动画面

ffmpeg - 如何使用 gstreamer (RTMP) 流式传输连接到树莓派的 USB 网络摄像头

node.js html-pdf 调用 pdfToFile 时出现 "spawn ENOTDIR"错误

node.js - nodemon 过滤样式文件更改

javascript - 为什么现在命令行的每个参数后面都有两个连字符 (--)?它起源于何处,为什么不使用单个连字符?

json - Express.Js 可以输出缩小的 JSON 吗?

PHP ffmpeg 转换错误