【问题标题】:child_process.on('close') is sometimes painfully slowchild_process.on('close') 有时非常缓慢
【发布时间】:2020-02-26 16:08:39
【问题描述】:

我有一个打开外部程序(在我的情况下为 Office)的电子应用程序,并且必须等待程序关闭。

我编写的代码运行良好,但有时child_process.on('close') 事件会在程序关闭后 10 或 20 秒触发。代码是:

const cp = require("child_process");
child = cp.spawn(path/to/Office.exe + ' "' + path/to/myFile.pptx + '"', {shell: true});
child.on('close', function (code) {
    //do something
});

大多数情况下它会在 1 或 2 秒后做出反应,这很好,但有时需要 20 秒才能收到关闭事件。程序关闭很快(根据任务管理器),但节点似乎在等待什么。

我还尝试了child.on('exit'),使用cp.exec() 调用程序并使用options.stdio: ignore 生成,因为我认为节点可能正在等待来自孩子的一些流。但这并没有什么不同。

有人知道加快这个过程的安全方法吗?

【问题讨论】:

  • 要考虑的另一件事是您的代码中可能存在“内存消耗”或同步的内容。这可能会对节点造成影响。
  • 我当时在 chromiums 调试器的性能监视器上记录。 chrome 中绝对没有。

标签: node.js electron child-process


【解决方案1】:

我已经尝试过您的代码,close 事件会以 0.5-2 秒的延迟触发,我会说可以忍受。

但是,20s 的延迟并没有发生,但是如果这个问题仍然存在,你可以尝试下面的方法,包括检查 spawn pid。

const pidExists = (pid) => {
    let pidOk = true;
    try {
        process.kill(pid, 0);
    } catch (e) {
        pidOk = false;
    }
    return pidOk;
};
const cp = require("child_process");
// I added the detach option because we won't need that process anymore since we're following the PID.
let child = cp.spawn(path/to/Office.exe + ' "' + path/to/myFile.pptx + '"', {shell: true, detach: true});
let officePID = child.pid; // this is the spawn pid

setInterval(()=>{
    if( pidExists(officePID)){
        console.log('file is still open', new Date().getTime());
    }else{
        console.log('file was closed', new Date().getTime());
        process.exit(0);
    }
}, 500);

这是一种更好的方法,因为您说任务管理器会显示程序已关闭。

【讨论】:

  • 这是一个有趣的方法。如果我能适应它,我会尝试。 PID 当然来自 shell,而不是 Office。因此发送终止信号会使我的应用程序崩溃(无论出于何种原因)。但是对于观察时间卡在哪里非常方便。
  • 是的,它是 shell pid,我只是希望它与电子分离,以确保应用程序不会干扰它,并且由于你有 shell pid,现在它只是一个监控游戏。只需将process.exit 替换为回调/方法或其他东西,我在测试时使用了 process.exit。 pidExists 不会退出主应用
猜你喜欢
  • 2012-06-13
  • 2010-10-24
  • 2016-11-25
  • 1970-01-01
  • 2023-01-24
  • 2021-11-11
  • 2019-08-11
  • 2010-10-31
  • 1970-01-01
相关资源
最近更新 更多