2012-10-13 27 views
1

在我的應用程序即時通信開放Wireshark的過程,並開始捕捉packts,在UI我有開始按鈕誰開始拍攝和停止按鈕誰停止捕獲和我我是通過殺死我的wireshark進程來做到這一點的。 我的問題是,如果我靠近在捕獲的中途我的應用程序,但也不符合我的停止按鈕,我的Wireshark的過程中繼續運行,我該怎麼處理這種情況,並確保我的進程將關閉,如果我的應用程序崩潰或你身邊它捕捉如何確保我的過程,我開始將關閉我的應用程序崩潰的

public void startCapturing() 
{    
    ThreadStart tStarter = delegate { openAdapterForStatistics(_device); }; 
    Thread thread = new Thread(tStarter); 
    thread.IsBackground = true; 
    thread.Start(); 
    ProcessStartInfo tsharkStartInfo = new ProcessStartInfo(); 
    tsharkStartInfo.FileName = _tshark; 
    tsharkStartInfo.RedirectStandardOutput = true; 
    tsharkStartInfo.RedirectStandardError = true; 
    tsharkStartInfo.RedirectStandardInput = true; 
    tsharkStartInfo.UseShellExecute = false; 
    tsharkStartInfo.CreateNoWindow = true; 
    tsharkStartInfo.Arguments = string.Format(" -i " + _interfaceNumber + " -s " + _packetLimitSize + " -w " + _pcapPath); 
    _tsharkProcess.StartInfo = tsharkStartInfo; 
    _tsharkProcess.ErrorDataReceived += _cmdProcess_ErrorDataReceived; 
    _tsharkProcess.OutputDataReceived += tshark_OutputDataReceived; 
    _tsharkProcess.EnableRaisingEvents = true; 
    _tsharkProcess.Start(); 
    _tsharkProcess.BeginOutputReadLine(); 
    _tsharkProcess.BeginErrorReadLine();     
    FileInfo fileInfo = new FileInfo(_pcapPath); 
    string directoryName = fileInfo.DirectoryName; 
    DirectoryInfo directoryInfo = new DirectoryInfo(directoryName); 
    FileInfo[] dirs = directoryInfo.GetFiles(); 
    _file = dirs.FirstOrDefault(f => f.Name.Equals(fileInfo.Name)); 
    _tsharkProcess.WaitForExit(); 
} 

回答

2

假設你正在使用try-catch異常處理的中間,你可以確保Wireshark的過程在finally塊在你最上面的try-catch發言結束時關閉。從MSDN文檔:

「finally塊清理try塊分配的資源有用的控制總是傳遞到finally塊不管如何try塊退出的。」

例如:

try 
{ 
    // Your application's code. 
} 
catch(Exception) 
{ 
    // Handle, log, whatever. 
} 
finally 
{ 
    // Make sure Wireshark process is killed. 
} 

finally塊中的代碼總是會得到執行是否存在是個例外。

+0

誰打開的過程中我的Wireshark類有開始捕獲方法和殺方法,以便在那裏把這個代碼? – user1710944

+0

這真的取決於你的代碼的結構。我不知道你的代碼的結構,所以我不能肯定地說。如果你想確保Wireshark被關閉,無論拋出什麼異常,你都需要把這個'try-catch-finally'放在你控制的最高點。例如,如果它是一個控制檯應用程序,你應該把它放在Main方法中。如果它是一個GUI應用程序,則主窗體的OnLoad事件可能會起作用。 – jebar8

+0

我更新我的代碼並添加我的開始捕獲方法(Tshark類的一部分) – user1710944

1

你不能100%肯定。如果你的應用程序以'文明'的方式崩潰,你可以關閉Wireshark進程(很像@ jebar8建議的)。不幸的是,你的應用程序可能會以不能運行finally代碼的方式崩潰(例如,如果它的內存不足或主線程超出堆棧空間)。

如果要考慮到這一點,以及,你需要第三個過程。編寫一個小程序,啓動您的應用程序並對其進行監控。如果你的應用程序過程消失了,你的監控過程就可以殺死Wirehsark。由於監測計劃簡短而簡單,因此意外崩潰的機會非常渺茫。