From 934cb6d2f8cbe87ded2d0fc0fe8c1a48e9ca25e6 Mon Sep 17 00:00:00 2001 From: Poised_flw Date: Fri, 3 Dec 2021 22:57:20 +0800 Subject: [PATCH] =?UTF-8?q?update:=20=E7=BB=A7=E7=BB=AD=E5=AE=8C=E5=96=84e?= =?UTF-8?q?lectron=E8=B0=83=E8=B5=B7=E5=A4=96=E9=83=A8=E5=BA=94=E7=94=A8?= =?UTF-8?q?=E5=8F=8A=E8=8E=B7=E5=8F=96=E6=89=A7=E8=A1=8C=E7=BB=93=E6=9E=9C?= =?UTF-8?q?=E7=A4=BA=E4=BE=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/main/child_process.js | 28 ++++++++++++++++++++++++---- app/main/ipc.js | 11 ++++++++--- 2 files changed, 32 insertions(+), 7 deletions(-) diff --git a/app/main/child_process.js b/app/main/child_process.js index a3b8452..173a022 100644 --- a/app/main/child_process.js +++ b/app/main/child_process.js @@ -1,17 +1,37 @@ const { spawn } = require('child_process') let pidMap = {} -function start(command, args) { +/** + * options: { onSuccess: null | function, onError: null | function, onClose: null | function } + */ +function start(command, args, options = {}) { const childProgress = spawn(command, args) pidMap[childProgress.pid] = childProgress + + childProgress.stdout.on('data' data => { + options.onSuccess && options.onSuccess(data) + }) + + childProgress.stderr.on('data', data => { + options.onError && options.onError(data) + }) + + childProgress.on('close', code => { + options.onClose && options.onClose(code) + }) + return childProgress.pid } function kill(pid) { const childProgress = pidMap[pid] - if (!childProgress || childProgress.killed) return; - // TODO 需要测试是否能真正杀掉 - return childProgress.kill() + let status = false + if (childProgress && !childProgress.killed) { + status = childProgress.kill() + } + childProgress = null + delete pidMap[pid] + return status } module.exports = { diff --git a/app/main/ipc.js b/app/main/ipc.js index e63840a..6178124 100644 --- a/app/main/ipc.js +++ b/app/main/ipc.js @@ -211,15 +211,20 @@ module.exports = () => { // // ipcMain.handle('removeApp', removeApp); - /* 示例 + /* 示例:在网页中调用ipcRenderer模块 ipcRenderer.send('spawn', { command: '微信.exe', args: null || ['--disable-cache'], - key: + new Date // 唯一key,用来做关闭识别 + key: + new Date // 唯一key,用来做关闭识别, + options: { + onSuccess: data => {}, // 正常执行回调 + onError: err => {}, // 错误执行回调 + onClose: code => {}, // 关闭回调 + } }) */ ipcMain.on('spawn', (event, arg) => { - const pid = childProcess.start(arg.command, arg.args) + const pid = childProcess.start(arg.command, arg.args, arg.options) event.sender.send('spawn-success', { key: arg.key, pid