简体   繁体   中英

NodeJS Kill Forever Running Child Process

I am using Wireshark's Tshark cmd tool to capture some network packets and analyze them. In order to generate working environment, you only need Wireshark 3+ and NodeJS 9+. I am using following code to cut the Tshark flow at a certain time (setTimeout is used to simulate a simultaneous Stop button click of the user)

var spawn = require('child_process').spawn,
ts = spawn('tshark', ['-i', 'Wi-Fi', '-T', 'json']);

function analyzePacket(packet) {
    console.log(packet.toString());
}

ts.stdout.on('data', function (packet) {
    analyzePacket(packet)
});

setTimeout(function(){ ts.kill(); }, 5000);

This works well however, when the ts.kill(); is called, writing the packet information to the screen is cut in the middle. I want the tshark to fully output the last packet that is captured before stop button (ts.kill() is fired) is clicked. I tried sending different kind of signals which differs in the killing harshness as far as I know. That are the following :

ts.kill('SIGINT');
ts.kill('SIGHUP');
ts.kill('SIGKILL');

None of them seems to be working. That is the best way to achieve final packet fully, then close gracefully.

Nature of Tshark

tshark will always be in the middle of parsing packets when it's capturing. There's not really a way for you to ask it to finish parsing a packet before killing it. If you want it to exit gracefully after a condition, -a duration:NUM will stop after NUM seconds and -c NUM will stop after NUM packets.

Possible Solution

If you absolutely need that packet that came in when the user hit the kill button, why not wait 100ms after you receive the signal and then then kill? This will capture the packet in question and won't be noticeable to the user.

Instead of killing process in setTimeout create a function and call that function when data is received.

function killPocess(){
  ts.kill();
}
function analyzePacket(packet) {
    console.log(packet.toString());
   killPocess(); // kill the process as packet is received
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM