From 36d5e8f73087fee78a8da4c0d9f2400d7018aefc Mon Sep 17 00:00:00 2001 From: antelle Date: Fri, 23 Apr 2021 23:49:14 +0200 Subject: [PATCH] windows process information --- desktop/scripts/util/process-utils.js | 52 +++++++++++++++++++++++---- 1 file changed, 46 insertions(+), 6 deletions(-) diff --git a/desktop/scripts/util/process-utils.js b/desktop/scripts/util/process-utils.js index b2793904..08f92b2b 100644 --- a/desktop/scripts/util/process-utils.js +++ b/desktop/scripts/util/process-utils.js @@ -2,24 +2,44 @@ const childProcess = require('child_process'); function getProcessInfo(pid) { return new Promise((resolve, reject) => { - const process = childProcess.spawn('/bin/ps', ['-opid=,ppid=,command=', '-p', pid]); + let cmd, args, parseOutput; + if (process.platform === 'win32') { + cmd = 'wmic'; + args = [ + 'process', + 'where', + `ProcessId=${pid}`, + 'get', + 'ProcessId,ParentProcessId,CommandLine', + '/format:value' + ]; + parseOutput = parseWmicOutput; + } else { + cmd = '/bin/ps'; + args = ['-opid=,ppid=,command=', '-p', pid]; + parseOutput = parsePsOutput; + } + const ps = childProcess.spawn(cmd, args); const data = []; - process.stdout.on('data', (chunk) => data.push(chunk)); + ps.stdout.on('data', (chunk) => data.push(chunk)); - process.on('close', () => { + ps.on('close', () => { const output = Buffer.concat(data).toString(); try { - const result = parsePsOutput(output); + const result = parseOutput(output); if (result.pid !== pid) { - throw new Error(`PS pid mismatch: ${result.pid} <> ${pid}`); + throw new Error(`PID mismatch: ${result.pid} <> ${pid}`); + } + if (!result.commandLine) { + throw new Error(`Could not get command line for process ${pid}`); } resolve(result); } catch (e) { reject(e); } }); - process.on('error', (e) => { + ps.on('error', (e) => { reject(e); }); }); @@ -37,4 +57,24 @@ function parsePsOutput(output) { }; } +function parseWmicOutput(output) { + const result = {}; + const keyMap = { + ProcessId: 'pid', + ParentProcessId: 'parentPid', + CommandLine: 'commandLine' + }; + for (const line of output.split(/\n/)) { + const match = line.trim().match(/^([^=]+)=(.*)$/); + if (match) { + const [, key, value] = match; + const mapped = keyMap[key]; + if (mapped) { + result[mapped] = mapped.endsWith('id') ? value | 0 : value; + } + } + } + return result; +} + module.exports = { getProcessInfo };