views:

100

answers:

4

I have written a program a.exe which launches another program I wrote, b.exe, using the CreateProcess function. The caller creates two pipes and passes the writing ends of both pipes to the CreateProcess as the stdout/stderr handles to use for the child process. This is virtually the same as the Creating a Child Process with Redirected Input and Output sample on the MSDN does.

Since it doesn't seem to be able to use one synchronization call which waits for the process to exit or data on either stdout or stderr to be available (the WaitForMultipleObjects function doesn't work on pipes), the caller has two threads running which both perform (blocking) ReadFile calls on the reading ends of the stdout/stderr pipes; here's the exact code of the 'read thread procedure' which is used for stdout/stderr (I didn't write this code myself, I assume some colleague did):

DWORD __stdcall ReadDataProc( void *handle )
{
    char buf[ 1024 ];
    DWORD nread;
    while ( ReadFile( (HANDLE)handle, buf, sizeof( buf ), &nread, NULL ) &&
            GetLastError() != ERROR_BROKEN_PIPE ) {
        if ( nread > 0 ) {
            fwrite( buf, nread, 1, stdout );
        }
    }
    fflush( stdout );
    return 0;
}

a.exe then uses a simple WaitForSingleObject call to wait until b.exe terminates. Once that call returns, the two reading threads terminate (because the pipes are broken) and the reading ends of both pipes are closed using CloseHandle.

Now, the problem I hit is this: b.exe might (depending on user input) launch external processes which live longer than b.exe itself, daemon processes basically. What happens in that case is that the writing ends of the stdout/stderr pipes are inherited to that daemon process, so the pipe is never broken. This means that the WaitForSingleObject call in a.exe returns (because b.exe finished) but the CloseHandle call on either of the pipes blocks because both reading threads are still sitting in their (blocking!) ReadFile call.

How can I solve this without terminating both reading threads with brute force (TerminateThread) after b.exe returned? If possible, I'd like to avoid any solutions which involve polling of the pipes and/or the process, too.

UPDATE: Here's what I tried so far:

  1. Not having b.exe inherit a.exe; this doesn't work. the MSDN specifically says that the handles passed to CreateProcess must be inheritable.
  2. Clearing the inheritable flag on stdout/stderr inside b.exe: doesn't seem to have any effect (it would have surprised me if it did).
  3. Having the ReadDataProc procedure (which reads on both pipes) consider whether b.exe is actually running in addition to checking for ERROR_BROKEN_PIPE. This didn't work of course (but I only realized afterwards) because the thread is blocked in the ReadFile call.
+1  A: 

Check the opensource library libexecstream http://libexecstream.sourceforge.net/

josuegomes
+1 - thanks for the pointer! I didn't try it yet, and I fear that it will be a bit overkill to use a whole new library for this problem, but studying the source code might give some insight. Thank you for pointing this out.
Frerich Raabe
I was curious and I checked - TerminateThread is used to stop blocking ReadFile.
adf88
@adf88: Thanks for checking. +1 for you. :-)
Frerich Raabe
+2  A: 
  1. Use named pipe and asynchronous ReadFile
    or
  2. Parse the output read from the pipe looking for the end (it may be too complicated in your case).
adf88
+1: Parsing the pipe output, looking for an 'end of process' marker, is a creative idea. ;-)
Frerich Raabe
+1  A: 

What happens in that case is that the writing ends of the stdout/stderr pipes are inherited to that daemon process, so the pipe is never broken.

Daemons should close their inherited file descriptors.

Roman Cheplyaka
+1: This is an interesting point of view; for what it's worth, the daemon program which `b.exe` launches is the program of a customer. However, before blaming him, I'd like to have some more arguments to support this claim. Do you happen to have a link to some explanation, or maybe you can extend your reply a bit?
Frerich Raabe
Becoming a daemon means making some operations ("daemonizing") and closing inherited file descriptors is one of them (on UNIX they are often redirected from/to `/dev/null` rather than closed). I believe this is taught in every book on UNIX system programming (yup, I remember you are concerned with windows, but the notion of daemon initially came from UNIX). (Splitting comment due to the length restriction)
Roman Cheplyaka
For online reference you can use Wikipedia article https://secure.wikimedia.org/wikipedia/en/wiki/Daemon_(Unix)#Types_of_daemons and references it contains.You can google a lot of HOWTOs on writing daemons, like this: http://www.cs.aau.dk/~adavid/teaching/MTP-05/exercises/10/Linux-Daemon_Writting.pdf (section 4.6 "Closing Standard File Descriptors")
Roman Cheplyaka
By the way, if you don't want to mess with your customer, you can close file descriptors by yourself. On UNIX this would look like:fork (create a copy of the current process);in the child process:close file descriptors (or redirect them);exec "b.exe" (execute the code of b.exe in the current (child) process). Since windows lack fork/exec calls, there is probably some equivalent of this sequence of operations.
Roman Cheplyaka
A: 

Is seems that on Windows versions prior to Windows Vista (where you can use the CancelSynchronousIO function, there is no way around terminating the reading threads using TerminateThread.

A suitable alternative (suggested by adf88) might be to use asynchronous ReadFile calls, but that's not possible in my case (too many changes to the existing code required).

Frerich Raabe