Graceful kill of a detached node.js spawned child process in Windows -
not duplicate of this: can kill process fine, want know how detect, within process, it's being killed, , gracefully shutdown.
overview:
i have cli tool spawn , kill child node.js process. demo code contained in these 3 files:
spawn.js -- spawn child.js script, detached. simplicity, pipe child's stdio out.log file
child.js -- simple counter writes file, uses readline method detect emulated sigint in windows
kill.js -- invokes process.kill() on child process, using it's pid
code:
spawn.js
'use strict'; var spawn = require('child_process').spawn; var fs = require('fs'); var path = require('path'); var childfilepath = path.resolve(__dirname, 'child.js'); var out = fs.opensync('./out.log', 'a'); var err = fs.opensync('./out.log', 'a'); var options = { detached: true, stdio: ['ignore', out, err], }; var child = spawn(process.execpath, [childfilepath], options); child.unref(); child.js
'use strict'; var fs = require('fs'); var path = require('path'); if (process.platform === 'win32') { console.log('win32 true'); var rl = require('readline').createinterface({ input: process.stdin, output: process.stdout, }); rl.on('sigint', function() { process.emit('sigint'); }); } process.on('sigint', function() { console.log('sigint'); process.exit(); }); var filepath = path.resolve(__dirname, 'pid.txt'); fs.writefile(filepath, process.pid); var = 0; setinterval(function () { console.log(i++); }, 1000); kill.js
'use strict'; var fs = require('fs'); var path = require('path'); var pidpath = path.resolve(__dirname, 'pid.txt'); fs.readfile(pidpath, 'utf8', function (err, data) { if (err) { return console.log(err); } process.kill(data, 'sigint'); }); problem:
when sending process.kill(pid, 'sigint'), doesn't detect sigint in windows. can run child.js manually , use ctrl+c kill process trigger sigint, know readline code working (or maybe not since sigint trigger without readline code, nonetheless trigger sigint)
does process.kill() not send type of signal detached process? how detect that separate script trying kill child process , shutdown gracefully?
Important to find a Node.js developer who is passionate and is always willing to explore and learn new things.Above all, the candidate has to have a team spirit and be a team player.
ReplyDeletenode.js development company