1'use strict'; 2const common = require('../common'); 3const assert = require('assert'); 4const child_process = require('child_process'); 5const cluster = require('cluster'); 6 7if (!process.argv[2]) { 8 // It seems Windows only allocate new console window for 9 // attaching processes spawned by detached processes. i.e. 10 // - If process D is spawned by process C with `detached: true`, 11 // and process W is spawned by process D with `detached: false`, 12 // W will get a new black console window popped up. 13 // - If D is spawned by C with `detached: false` or W is spawned 14 // by D with `detached: true`, no console window will pop up for W. 15 // 16 // So, we have to spawn a detached process first to run the actual test. 17 const primary = child_process.spawn( 18 process.argv[0], 19 [process.argv[1], '--cluster'], 20 { detached: true, stdio: ['ignore', 'ignore', 'ignore', 'ipc'] }); 21 22 const messageHandlers = { 23 workerOnline: common.mustCall(), 24 mainWindowHandle: common.mustCall((msg) => { 25 assert.match(msg.value, /0\s*/); 26 }), 27 workerExit: common.mustCall((msg) => { 28 assert.strictEqual(msg.code, 0); 29 assert.strictEqual(msg.signal, null); 30 }) 31 }; 32 33 primary.on('message', (msg) => { 34 const handler = messageHandlers[msg.type]; 35 assert.ok(handler); 36 handler(msg); 37 }); 38 39 primary.on('exit', common.mustCall((code, signal) => { 40 assert.strictEqual(code, 0); 41 assert.strictEqual(signal, null); 42 })); 43 44} else if (cluster.isPrimary) { 45 cluster.setupPrimary({ 46 silent: true, 47 windowsHide: true 48 }); 49 50 const worker = cluster.fork(); 51 worker.on('exit', (code, signal) => { 52 process.send({ type: 'workerExit', code: code, signal: signal }); 53 }); 54 55 worker.on('online', (msg) => { 56 process.send({ type: 'workerOnline' }); 57 58 let output = '0'; 59 if (process.platform === 'win32') { 60 output = child_process.execSync( 61 'powershell -NoProfile -c ' + 62 `"(Get-Process -Id ${worker.process.pid}).MainWindowHandle"`, 63 { windowsHide: true, encoding: 'utf8' }); 64 } 65 66 process.send({ type: 'mainWindowHandle', value: output }); 67 worker.send('shutdown'); 68 }); 69 70} else { 71 cluster.worker.on('message', (msg) => { 72 cluster.worker.disconnect(); 73 }); 74} 75