Electron JS子进程没有被杀死

时间:2020-05-04 09:14:42

标签: javascript node.js electron

我正在编写一个电子js脚本来运行.exe文件。想法是,当我单击“开始”按钮时,.exe应该作为子进程启动,而当我单击“停止”时,子进程应该被杀死。

我正在使用IPC进行通信。

const getScriptPath = () =>{
  if(process.platform==='win32'){
    return path.join(__dirname, 'dist_folder','pydoc.exe')

  }
}

const createPyProc =() =>{
  let script = getScriptPath()
  pyProc = require('child_process').execFile(script)  
  allProcess.push(pyProc)  

  }

}

const exitPyProc=() => {

    allProcess.forEach(function(proc){
      proc.kill();
    });


}
ipc.on('start_script',function(event){
  createPyProc()

})

ipc.on('stop_script', function(event){
  exitPyProc()

})

当我单击启动按钮时,我可以在任务管理器中看到子进程在电子主进程下启动,并且在按下kill按钮后被杀死。

问题: 1.即使我关闭了电子子进程已经被杀死的电子窗口,pydoc.exe的任务管理器中仍然残留有一个独立的进程。

我的子进程命令正确吗?

 pyProc = require('child_process').execFile(script)  

1 个答案:

答案 0 :(得分:0)

  const subprocess = spawn(getScriptPath(), args);

  subprocess.stdout.on('data', data => {
    console.log(`Daemon stdout: ${data}`);
    resolve(data.toString());
    // Here is where the output goes
  });
  subprocess.stderr.on('data', data => {
    console.log(`Daemon stderr: ${data}`);
    resolve(data.toString());
    // Here is where the error output goes
  });
  subprocess.on('close', code => {
    console.log(`Successfully closed. ${code}`);
    // Here you can get the exit code of the script
  });

  ipc.on('stop_script', function(event){
    subprocess.kill(); 
  })