views:

367

answers:

2

I am using the Process class to run an exe.

The exe is a 3rd party console application that I do not control.

I wish to know whether the process is waiting for input on the command line.

Should it make any difference, I intend to kill the application should it be waiting for input.

There are suitable events for when there is output from the program waiting to be read, but I cannot see anything similar for when the process is waiting patiently for input.

            ProcessStartInfo info = new ProcessStartInfo();
            info.FileName = "myapp.exe";
            info.CreateNoWindow = true;
            info.UseShellExecute = false;
            info.RedirectStandardError = true;
            info.RedirectStandardInput = true;
            info.RedirectStandardOutput = true;
            process.StartInfo = info;

            process.OutputDataReceived += new DataReceivedEventHandler(process_OutputDataReceived);
            process.ErrorDataReceived += new DataReceivedEventHandler(process_ErrorDataReceived);

            process.Start();

            process.BeginOutputReadLine();
            process.BeginErrorReadLine();


            process.WaitForExit();

How do I detect that my process is waiting for input?

+2  A: 

Depending on what the 3rd party process is doing exactly you could try polling its threads' states:

foreach(ProcessThread thread in process.Threads)
    if (thread.ThreadState == ThreadState.Wait
        && thread.WaitReason == ThreadWaitReason.UserRequest)
            process.Kill();

Failing that... you can try to

process.StandardInput.Close();

after calling Start(), I conjecture that an exception will be raised in the child process if it's trying to read from standard input.

Serguei
This appears to work in my test rig. I'll try it vs. the actual program causing me problems next.For info: Using process.StandardInput.Close() my program being run didn't receive an exception, it just stopped running quietly.
Don Vince
+2  A: 

If the console application has some sort of prompt waiting for input, you could periodically parse out the console output text using the Process.StandardOutput property of the process and wait for said prompt. Once the proper string is detected, you know that it's waiting for input. See http://msdn.microsoft.com/en-us/library/system.diagnostics.process.standardoutput.aspx.

nithins
Great approach. It doesn't address my issue, but is a valid approach for situations where you can bank on the output. Thanks again.
Don Vince