0

我正在使用 Tshark 开始使用 CommandLine 进行捕获,并使用此进程的输出计算接收到的数据包编号:我的 StreamReader 读取进程的输出并在此输出中解析数据包编号,以便在我的表单上显示此编号。我的问题是在我终止进程之后,我显示的数据包数量与文件中的实际数据包(pcap 文件)之间存在差异所以我的问题是是否有办法终止进程但等到所有进程输出完成。

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...            
    }
}
4

1 回答 1

1

与其终止进程,不如优雅地关闭它。期望你刚刚杀死的东西继续与你交谈有点过分。

你必须想出一些方法来优雅地结束这个过程。究竟如何最好地做到这一点,我无法从这里判断。

使用数据包捕获库而不是依赖外部控制台应用程序可能更合适。例如 pcap.net。我敢肯定还有其他的库。

于 2012-09-29T18:46:20.423 回答