简体   繁体   English

NodeJS永远杀死正在运行的子进程

[英]NodeJS Kill Forever Running Child Process

I am using Wireshark's Tshark cmd tool to capture some network packets and analyze them. 我正在使用Wireshark的Tshark cmd工具捕获一些网络数据包并进行分析。 In order to generate working environment, you only need Wireshark 3+ and NodeJS 9+. 为了生成工作环境,您只需要Wireshark 3+和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) 我正在使用以下代码在特定时间剪切Tshark流(setTimeout用于模拟用户同时单击“停止”按钮)

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(); 但是,当ts.kill();时,这很好用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. 我希望tshark完全输出在单击停止按钮(触发ts.kill())之前捕获的最后一个数据包。 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. tshark在捕获时将始终处于解析数据包的中间。 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. 如果希望它在某个条件后正常退出,则-a duration:NUM将在NUM秒后停止,而-c NUM将在NUM个数据包后停止。

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? 如果您绝对需要用户按下“停止”按钮时进入的数据包,为什么不等收到信号后等待100毫秒再杀死呢? 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. 创建一个函数并在接收到数据时调用该函数,而不是在setTimeout中终止进程。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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