【问题标题】:How can I spawn a child process that starts an electron app and then kill it while keeping the parent process alive?如何生成一个启动电子应用程序的子进程,然后在保持父进程存活的同时杀死它?
【发布时间】:2019-05-08 21:10:44
【问题描述】:

我有一个启动(生成)电子应用程序(子)的主进程,我正在尝试杀死它,同时让父进程在一段时间后保持活力。我总是只杀死父母,在阅读了很多文章(也在 stackoverflow 上)之后,我唯一获得的成就就是我杀死了他们两个。但我需要让父母活着。我希望能够杀死不再响应或崩溃的子进程。

我尝试分叉但也尝试生成。 我在 parent.js 中尝试了所有这些(代码如下):

杀死两者:

process.kill(-script.pid);

只杀死父母:

kill(-script.pid, SIGKILL);

只杀死父级(脚本是来自 script = spawn(...) 的子级):

script.stdin.pause();
script.kill();

父.js:

let spawn = require('child_process').spawn;

console.log('main process started.');

let script = spawn('npm', ["start"], {detached: true});

setTimeout(function(){

  //This one kills both
  process.kill(-script.pid);

  }, 3000);

child.js:

const exec = require('child_process').exec;

exec('cd $HOME/Desktop/Myapp && npm start');

我希望父进程始终处于活动状态并随时终止子进程。 我知道这很基础,但即使经过深入研究和阅读,我也无法让它发挥作用。

这可能与 Electron 有关吗?

【问题讨论】:

    标签: node.js electron


    【解决方案1】:

    我自己找到了一种可能的解决方案。对于那些有兴趣的人。

    我使用这两个模块:

    const findProcess = require('find-process');
    const ps = require('ps-node');
    

    我基本上使用 findProcess 按名称查找 PID,然后使用 ps 杀死与此相关的所有进程。

    findProcess('name', "Electron")
        .then(function (list) {
    
          for(var i=0; i<list.length; i++){
    
            console.log(list[i].pid);
            pidToKill = list[i].pid;
            pidToKill = pidToKill.toString();
    
            ps.kill( pidToKill, {
              signal: 'SIGKILL',
              timeout: 10,  // will set up a ten seconds timeout if the killing is not successful
            }, function(){});
    
          }
        }, function (err) {
          console.log(err.stack || err);
        });
    
    

    这对您也有帮助,或者您有更好的解决方案。 如果有更好的解决方案,那么我很高兴听到它们。

    谢谢

    【讨论】:

      猜你喜欢
      • 2012-08-04
      • 2020-06-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多