即使在进程终止后也能获得所有进程输出

时间:2012-09-29 18:34:24

标签: c# wireshark

我正在使用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...            
    }
}

1 个答案:

答案 0 :(得分:1)

而不是杀死进程,优雅地关闭它。期待你刚刚杀死的东西继续跟你说话有点太多了。

你必须想出一些方法来优雅地关闭这个过程。究竟如何最好地做到这一点,我不能从这里说出来。

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