3

I'm trying to write a C# wrapper for Iperf server. After Iperf client is done with packet sending, the C# server application should dump the output data to the text file. The problem is that this process (server) never exits, so it doesn't dump any data to the txt file. However, when I manually close the cmd window that runs iperf server, the text file is written with data (process exits). But this is clearly not the solution I'm looking for. Any suggestions how can I write the data directly into the file, w/o need of manually closing the iperf server cmd window?

This is my code:

private void button1_Click(object sender, EventArgs e)
{       
    string commandline_server = " -s -u -i 1";

    try
    {        
        process = new Process();
        process.StartInfo.FileName = "iperf.exe";
        process.StartInfo.UseShellExecute = false;
        process.StartInfo.RedirectStandardOutput = true;
        //process.StartInfo.RedirectStandardError = true;

        process.StartInfo.Arguments = commandline_server;
        process.StartInfo.CreateNoWindow = false;

        process.EnableRaisingEvents = true;
        process.Exited += new EventHandler(process_Exited);

        process.Start();              
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.ToString());
    }
}

void process_Exited(object sender, EventArgs e)
{
    //throw new NotImplementedException();
    string outfile = process.StandardOutput.ReadToEnd();
    System.IO.File.WriteAllText("test.txt", outfile);
}
Andrew Savinykh
  • 25,351
  • 17
  • 103
  • 158
stani
  • 111
  • 1
  • 1
  • 7
  • possible duplicate of [How to asynchronously read the standard output stream and standard error stream at once](http://stackoverflow.com/questions/12566166/how-to-asynchronously-read-the-standard-output-stream-and-standard-error-stream) – Andrew Savinykh Feb 16 '15 at 20:15
  • Thank you for your link, but this is not helping me much. It seems that the process (Iperf server) actually never exits, so it never raises an event. I'm wondering if there is a way to read the output continuously, without waiting for the process to exit? Thanks. – stani Feb 17 '15 at 04:33
  • It raises events all right. I pasted the code from the accepted answer into VS verbaitm, changed the file path, and the command line, added the textbox and button to the form and wired up the button to `StartProcess` method and added a new line after each line in the `Display` method. I immediately got [this](http://i.stack.imgur.com/78yAL.png). – Andrew Savinykh Feb 17 '15 at 05:41

1 Answers1

0

Instead of shelling out to a terminal, have you considered using their API? iperf3 introduced "libiperf".

There are example C-programs in their source code tree.

Nate
  • 18,892
  • 27
  • 70
  • 93