Nuance deadlock on console output redirection.

Source: Internet
Author: User

I helped a colleague on debugging the program she wrote. it's so weird that if we invoke the program directly by cmd.exe, it executes perfectly. however, if we invoke it from another program wrote by she, both programs just hung there.

 

I went through the code and there is nothing special. so I use windbg attached the child process and printed out call stack of every thread, I saw main thread was blocked on ntwritefile. so I checked the handle used by ntwritefile, but there was not
Much info useful. so I went ahead checked all critical sections but it seems there was no dead lock in the child process. I made a mistake here: I did not check the parent process to see where it's blocked!

 

Since nothing found via debugger, I went back to look at the codes and I see something like this in the parent process 'Code:

Process cp = Process.Start(CurrentCommand);cp.WaitForExit();RedirectStandard(cp);

Wow, seems there is something wrong. you can see that parent process is waiting for child process to exit so that it can read it output. what if the child process 'output buffer is full before it finishes its job and exit?

 

Things become clear here. after changing the sequence, the Hung issue gone. after that I seached the web for the buffer size, I did not find out the exact size of the buffer, but I did find out someone encounters the similar issue before, however, he/she
Used a different approach.

 

Ref link:

Http://stackoverflow.com/questions/139593/processstartinfo-hanging-on-waitforexit-why

 

Addtional notes:

If you only need to redirect only one of stdout/stderr, it's fine to simply switch the sequence of the wait for exit and the redirection. but if you need to redirect both of them, then you will need to implement an async redirection pattern, as the link
Provided.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.