【问题标题】:Killing a FFmpeg process triggered by spawn in NodeJs杀死由 NodeJs 中的 spawn 触发的 FFmpeg 进程
【发布时间】: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


    【解决方案1】:

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

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

    新版本的 ffmpeg 不再使用 'q' 了,至少在 Ubuntu 上是这样 Oneiric,相反,他们说要按 Ctrl+C 来阻止他们。所以用一个 较新的版本,您可以简单地使用 'killall -INT' 向他们发送 SIGINT 而不是 SIGTERM,它们应该干净地退出。


    所以拨打x.kill('SIGINT');

    【讨论】:

      猜你喜欢
      • 2023-03-22
      • 2016-10-28
      • 2014-09-30
      • 2018-05-07
      • 1970-01-01
      • 2015-04-18
      • 1970-01-01
      • 2015-10-17
      • 1970-01-01
      相关资源
      最近更新 更多