From 66df2fec88b8041de16b40b2e3f0f4a860a4c78a Mon Sep 17 00:00:00 2001 From: Poised_flw Date: Sun, 24 Oct 2021 21:36:46 +0800 Subject: [PATCH] add child_process spawn demo --- .gitignore | 1 + app/main/child_process.js | 20 ++++++++++++++++++++ app/main/ipc.js | 21 +++++++++++++++++++++ 3 files changed, 42 insertions(+) create mode 100644 .gitignore create mode 100644 app/main/child_process.js diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..1377554 --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +*.swp diff --git a/app/main/child_process.js b/app/main/child_process.js new file mode 100644 index 0000000..a3b8452 --- /dev/null +++ b/app/main/child_process.js @@ -0,0 +1,20 @@ +const { spawn } = require('child_process') +let pidMap = {} + +function start(command, args) { + const childProgress = spawn(command, args) + pidMap[childProgress.pid] = childProgress + return childProgress.pid +} + +function kill(pid) { + const childProgress = pidMap[pid] + if (!childProgress || childProgress.killed) return; + // TODO 需要测试是否能真正杀掉 + return childProgress.kill() +} + +module.exports = { + start, + kill, +} diff --git a/app/main/ipc.js b/app/main/ipc.js index f4598fa..e63840a 100644 --- a/app/main/ipc.js +++ b/app/main/ipc.js @@ -5,6 +5,7 @@ const store = require('./windows/lib/store'); const {create: createMainWindow} = require('./windows/main') // const { create: createLoginWindow } = require('./windows/login') // const { create: createAppWindow } = require('./windows/app') +const childProcess = require('./child_process') const {MAIN_WINDOW_FLAG, SUSPENSION_WINDOW_FLAG} = require('./constant'); // const installApp = require('./ipc/installApp'); @@ -209,4 +210,24 @@ module.exports = () => { // ipcMain.handle('getApps', getApps); // // ipcMain.handle('removeApp', removeApp); + + /* 示例 + ipcRenderer.send('spawn', { + command: '微信.exe', + args: null || ['--disable-cache'], + key: + new Date // 唯一key,用来做关闭识别 + }) + */ + ipcMain.on('spawn', (event, arg) => { + const pid = childProcess.start(arg.command, arg.args) + event.sender.send('spawn-success', { + key: arg.key, + pid + }) + }) + + // ipcRenderer.send('kill-process', [pid]) + ipcMain.on('kill-process', function (event, arg) { + childProcess.kill(arg[0]) + }) }