0

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 
0

2 Answers 2

3

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();
}
Sign up to request clarification or add additional context in comments.

3 Comments

I am sorry but what does this line actually means ?? if the process is not closed after 3000 milli seconds kill it ??
Correct; WaitForExit(3000) will wait for 3000 milliseconds for the process to exit and if it doesn't exit, it will return false; upon returning false, your application will then kill the process it just started.
Nice... Working perfectly dude :) :) Thank you
0

Does it work for you then you check

if (tcpdump.EndOfStream)
{
    // ...
}

before reading to the end?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.