1

import { spawn } from 'child_process'
let subproc = spawn( xxx/xxx.exe, [])

This code opens a new process of xxx.exe.

How can I destroy the child process automatically after the main process exits

1 Answers1

1
import findProcess from 'find-process'
import { exec } from 'child-process'

const stop = async () => {
    const yourSubProcessName = 'xxx'
    if(process.platform === 'win32') {
        // Consider OS type
        // This is just for WinOS
        exec(`taskkill /IM ${yourSubProcessName}`)
    } else {
        // Other OS
        exec(`kill xxx`)
    }

    while(1) {
        const processList = await findProcess('name', yourSubProcessName)
        if(processList.length === 0) break
    }

}

app.on('will-quit', async () => {
    await stop()
});
...

This is terminating the subProcess when the main app is closing. Listen then will-quit event and terminate the subProcess on handler.

This code is to close the subprocess by ProcessName but you can change this as your needs.

And you should consider your running OS type.

tpikachu
  • 4,478
  • 2
  • 17
  • 42
  • Thank you, Pikachu.But this solution is violent,emm.. but but it's the simplest.If there is no better way, I will use this plan.Thank you, Pikachu – gao.xiangyang Feb 12 '20 at 18:40
  • Because the child process did not exit, `will-quit` could not be fired.I should listen `app.on('quit'()=>{})` – gao.xiangyang Feb 13 '20 at 02:45
  • @gao.xiangyang Yes, good to hear that. Actually, this `will-quit` event will be triggered before quit. But if this was not working. You can use your case. Thanks for letting me know – tpikachu Feb 13 '20 at 06:24
  • If the subprocess has other subprocess, using `taskkill /F /IM ${yourSubProcessName} /T` is not feasible,It is ok for me to use `taskkill /pid ${pid} /T /F`. I referred to Casper Beyer's question [Can't kill child process on Windows ](https://stackoverflow.com/questions/32705857/cant-kill-child-process-on-windows/32814686).I hope this problem can help people who encounter problems in the future.Off topic: My English is very poor. All the words are translated by Google. Hope you can understand. – gao.xiangyang Feb 13 '20 at 08:58