I am using Tshark to start capturing with CommandLine, with the output of this process I am calculating the received packets number: my StreamReader read the output of the process and inside this output parse the packet number in order to show this number on my form.
my problem is after I am kill the process there is different between the number of packets i am show and the actual packets inside the file (pcap file) so my question is if there is a way to kill the process but wait until all the process output finish.
public class Tshark
{
public int _interfaceNumber;
public string _pcapPath;
public int _test;
public int _packetsCount;
public string _packet;
public delegate void dlgPackProgress(int progress);
public event dlgPackProgress evePacketProgress;
public Tshark(int interfaceNumber, string pcapPath)
{
_interfaceNumber = interfaceNumber;
_pcapPath = pcapPath;
}
public void startTheCapture()
{
Process _tsharkProcess1 = new Process();
_tsharkProcess1.StartInfo.FileName = @"C:\Program Files\Wireshark\tshark.exe";
_tsharkProcess1.StartInfo.Arguments = string.Format(" -i " + _interfaceNumber + " -V -x -w " + _pcapPath);
_tsharkProcess1.OutputDataReceived += new DataReceivedEventHandler(process_OutputDataReceived);
_tsharkProcess1.StartInfo.RedirectStandardOutput = true;
_tsharkProcess1.StartInfo.UseShellExecute = false;
_tsharkProcess1.StartInfo.CreateNoWindow = true;
_tsharkProcess1.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
_tsharkProcess1.Start();
Thread.Sleep(2000);
DateTime lastUpdate = DateTime.MinValue;
StreamReader myStreamReader = _tsharkProcess1.StandardOutput;
while (!myStreamReader.EndOfStream)
{
_packet = myStreamReader.ReadLine();
if (_packet.StartsWith(" Frame Number:"))
{
string[] arr = _packet.Split(default(char[]), StringSplitOptions.RemoveEmptyEntries);
_test = int.Parse(arr[2]);
_packetsCount++;
}
if ((DateTime.Now - lastUpdate).TotalMilliseconds > 1000)
{
lastUpdate = DateTime.Now;
OnPacketProgress(_packetsCount++);
}
}
_tsharkProcess1.WaitForExit();
}
private void OnPacketProgress(int packet)
{
var handler = evePacketProgress;
if (handler != null)
{
handler(packet);
}
}
public void killProcess()
{
foreach (Process prc in System.Diagnostics.Process.GetProcessesByName("tshark"))
{
prc.Kill();
prc.WaitForExit();
}
}
private void process_OutputDataReceived(object sender, DataReceivedEventArgs arg)
{
string srt = arg.Data; //arg.Data contains the output data from the process...
}
}
Instead of killing the process, close it gracefully. It’s a bit much to expect something you just killed to carry on talking to you.
You’ll have to come up with some way to gracefully close the process. Exactly how is best to do that, I cannot tell from here.
It might be more appropriate to use a packet capture library rather than relying on external console apps. For example pcap.net. I’m sure there are other libs for this.