Windows -- inherit console file handle in child process

1.1k views Asked by At

I have a Windows application (subsystem=windows, not a console application). I am creating a console in that application, then creating a child process. When I create the console, I make a console file handle inheritable (see below). When I create the child process, I set the bInheritHandles argument of CreateProcess to TRUE. I want the child process to be able to read to and write from the console, but I get error 0x06, invalid handle.

I do the following:

1) AllocConsole();

2) CreateFile("CONIN$", ...), CreateFile("CONOUT$", ...) or CreateConsoleScreenBuffer(...) with the following SetConsoleActiveScreenBuffer(...). Always have SecurityAttributes with bInheritHandle=TRUE. but see bInheritHandle=1.

3) CreateProcess(NULL, GetCommandLine(), NULL, NULL, TRUE, /* inherit handles */ 0, NULL, NULL, &sinfo, &child);

In child process:

1) _open_osfhandle((intptr_t)console_handle, 0) gives me -1 and GetLastError() returns error 0x06 -- "Invalid handle".

The child process is a copy of its parent, so both processes have the same subsystem: windows (not console application).

I have checked that other file handles are inherited normally and can be used with fdopen(_open_osfhandle(file_handle), ...). For example, it works for a text file. But it doesn't work for a console handle.

What I am doing wrong?

1

There are 1 answers

0
Kirill Frolov On

Yes, arx (see comments above) absolutelly right: console file handle is "fake" handle as it not exists at OS level (and can not be inherited). This type of file handle is only known for Win32 api libraries (kernel32.dll) and I/O requests processed at this level only. Windows doesn't have real console files, as virtual terminals in Unix (except of Windows8). :-( So, I need to change subsystem of my application from "windows" type to "console" and then application can use pre-allocated console (but file handle still can't be inherited -- need to reopen "CONOUT$" in child process...)