简体   繁体   中英

How to avoid standard input getting stuck in c# process

I'm writing a program to check whether the submit code is right or not. Here is some of my code...

Process submitProg;
StreamWriter progInput;
string input;//it will be submitProg's standard input

//initialization
//...

submitProg.Start();
progInput = submitProg.StandardInput;
progInput.Write("{0}",input);
progInput.Close();
progInput.Dispose();


while(!submitProg.HasExited)
    if(timeOUT)
        submitProg.Kill();

Amazingly it will get stuck at the line progInput.Write("{0}",input); while input is big enough and the submit program didn't read anything.

Some submit code might be tricky like while(1); doing nothing. I can kill the process when the input file is small enough. On the contrary, if the input file is bigger, the program won't check for timeout and get stuck while reading input.

Do I have any solution to avoid getting stuck in the code that doesn't read anything. Thanks.

You're at the mercy of the size of the standard input buffer and the program you're testing. If it doesn't read its buffer, your write to the standard input can block.

One way to avoid that issue would be to write to the standard input stream on a different thread, eg a ThreadPool thread. Just place the Write, Close, Dispose lines in a ThreadPool task and use ThreadPool.QueueUserWorkItem.

As a side note, you probable don't need to call progInput.Close and ProgInput.Dispose. The Dispose call should be fine.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM