tags:

views:

49

answers:

1

I have a process that needs to launch a child process and communicate with it through standard input and output. The child process should be able to automatically terminate itself; however, I am having trouble closing the streams properly.

Here is the relevant code from the child / "client" process:

// This is started in a separate thread
private void watchStandardInput() {
    string line = null;
    do {
        try {
            line = Console.ReadLine();
        } catch (IOException) {
            return;
        }
        lock (inputWatcher) {
            switch (line) {
                // process command
            }
        }
    } while (line != null);
}

// This is called from the main thread
private void updateStatus(string statusMessage) {
    lock (inputWatcher) {
        Console.WriteLine(statusMessage);
    }
}

And here's the "server" code:

// This is in the main thread
using (StreamReader sr = process.StandardOutput) {
    while (!process.HasExited) {
        processOutput(sr.ReadLine());
    }
}

// Finally, commands are sent in a separate thread.

Now for the problem I am having: When the child process is supposed to be exiting, the server stays at sr.ReadLine() and the client stays at Console.ReadLine(). What am I doing wrong?

+1  A: 

Make sure the client thread doing the ReadLine() has IsBackground set to true. Do NOT do an Abort() / Join() on this thread. Just close down all non-background threads. I found that even with IsBackground set to true, doing an Abort() / Join() on the background thread caused my test app to wait for input, however, removing the Abort() / Join() and just exiting regularly worked fine.

Joel Rondeau
I was able to get something working by calling `Environment.Exit` in the child process when necessary, but this is a far better solution that I was not aware of. Thank you.
jnylen