Reputation: 325
I am using c# and StandardoutputRedirect to get the output of my process in a string, but the problem that the program sometimes doesn't give any output how ever the process still waiting for an output how can I for example wait for 3 seconds if there is no output continue the program??
Here is my code
Process tcpdump = new Process();
tcpdump.StartInfo.FileName= "/usr/sbin/tcpdump";
tcpdump.StartInfo.CreateNoWindow = true;
tcpdump.StartInfo.Arguments = " -i en1 -c 10 -nn tcp and src host " + ip + " and port " + ports[i];
tcpdump.StartInfo.UseShellExecute = false;
tcpdump.StartInfo.RedirectStandardOutput = true;
tcpdump.Start();
tcpdump.WaitForExit(3000);
string tcpdump_output = tcpdump.StandardOutput.ReadToEnd(); // at this part the programs waits for an output
Upvotes: 0
Views: 177
Reputation: 38416
You have tcpdump.WaitForExit(3000);
, which should only have your Process waiting for that long, but you may also want to kill it to move on:
if (!tcpdump.WaitForExit(3000)) {
tcpdump.Kill();
}
Also, per the documentation, you should call .StandardOutput.ReadToEnd()
before calling WaitForExit()
, otherwise you can enter a deadlock - which it appears you are. So, try updating your code to:
string tcpdump_output = tcpdump.StandardOutput.ReadToEnd();
if (!tcpdump.WaitForExit(3000)) {
tcpdump.Kill();
}
Upvotes: 3
Reputation: 2380
Does it work for you then you check
if (tcpdump.EndOfStream)
{
// ...
}
before reading to the end?
Upvotes: 0