【问题标题】:How to kill specific child process in react-electron如何杀死反应电子中的特定子进程
【发布时间】:2021-09-21 02:14:27
【问题描述】:

我的电子应用程序由“2 个你好”按钮和 2 个“取消”按钮组成。每个 'hello' 按钮都会触发一个执行相同功能的子进程,而取消按钮将杀死子进程。

我的问题是第二个“hello”按钮触发的功能可以被第一个取消按钮终止。

我想要的是第一个“取消”按钮只会杀死第一个“你好”按钮的子进程,依此类推。

我们将不胜感激任何建议和帮助。 谢谢

我的用户界面:

我的电子代码:

let process = null

ipcMain.on("runScript", (event, data) => {
   process = spawn('node helloworld.js', [], { shell: 
    true })
  });

ipcMain.on("killScript", (event, data) => {
    console.log(process)
    kill(process.pid, 'SIGKILL')


});

在我的客户端:

<div>
  <button onClick={() => ipcRenderer.send('runScript')}>hello</button>
  <button onClick={() => ipcRenderer.send('killScript')}>cancel</button>
</div>

【问题讨论】:

    标签: node.js reactjs electron child-process


    【解决方案1】:

    您需要注意一些事情,因为您要尝试生成多个进程,所以您需要将它们存储在一个数组而不是一个变量中,或者有 2 个变量,一个用于生成的每个按钮/进程,因为进程每次单击两个 hello 按钮中的任何一个时,之前位于 process 变量中的变量都会被覆盖,因为它们会发出相同的事件,并且会被 cancel 按钮中的任何一个杀死。

    如果您要拥有相同数量的按钮,即只有您创建的两个按钮,请执行以下操作:

    // Backend
    let process1, process2 = null
    
    ipcMain.on("runScript", (event, data) => {
       if(data.process == 1) process1 = spawn('node helloworld.js', [], { shell: 
        true });
       else if(data.process == 2) process2 = spawn('node helloworld.js', [], { shell: 
        true })
       
      });
    
    ipcMain.on("killScript", (event, data) => {
        if(data.process == 1) {
           kill(process1.pid, 'SIGKILL');
        } else if (data.process == 2) kill(process2.pid, 'SIGKILL');    
    });
    
    // Client side
    <div>
      <button onClick={() => ipcRenderer.send('runScript', {process: 1})}>hello</button>
      <button onClick={() => ipcRenderer.send('killScript', {process: 1})}>cancel</button>
    </div>
    <div>
      <button onClick={() => ipcRenderer.send('runScript', {process: 2})}>hello</button>
      <button onClick={() => ipcRenderer.send('killScript', {process: 2})}>cancel</button>
    </div>
    

    如果您要拥有可变数量的按钮,则需要在后端使用数组来实现相同的解决方案,并且{process: processNumber} 还需要对应于后端进程数组中的正确进程.

    【讨论】:

    • 非常感谢兄弟,您的解决方案非常完美!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-08
    • 1970-01-01
    • 2015-06-27
    • 2013-11-12
    • 1970-01-01
    • 2018-01-16
    相关资源
    最近更新 更多