简体   繁体   中英

How to NOT inherit stdin, stdout and stderr in CreateProcess() on Windows

CreateProcessW() , accepts a flag bInheritHandles . If it is set to FALSE , only stdin , stdout and stderr are inherited, the others are not.

This is sometimes annoying to inherit everything, so it is possible to explicitly configure the handles to inherit using extended startup info . In that case, stdin , stdout and stderr are not inherited by default, but they can be inherited by including them in the inherited handles in UpdateProcThreadAttribute() .

That way, it is possible to inherit only stderr for example.

But as a specific case, how to disable them all (including stdin , stdout and stderr )? UpdateProcThreadAttribute() fails if we pass a NULL /empty list for attribute PROC_THREAD_ATTRIBUTE_HANDLE_LIST .

Note that I don't want to redirect stdin , stdout and stderr in that case (I don't want to write to/read from them), I just want to disable them.

As a workaround, it is possible to create a dummy HANDLE and inherit it, so that stdin , stdout and stderr could be disabled, but it's a bit hacky. bInheritHandles set to FALSE does not work because it enables stdin , stdout and stderr . Passing DETACHED_PROCESS might have other side effects (?).

What is the correct way to achieve this?

Oh, if STARTF_USESTDHANDLES is set, and if bInheritHandles set to FALSE , then no handles are inherited at all, which is exactly what I want:

STARTUPINFOW si;
memset(&si, 0, sizeof(si));
si.cb = sizeof(si);

// This is important to disable stdin, stdout and stderr
si.StartupInfo.dwFlags = STARTF_USESTDHANDLES;

// si.hStdInput, si.hStdOutput and si.hStdError must not be set

EDIT: Alternatively, as mentioned here passing DETACHED_PROCESS in dwCreationFlags (a parameter of CreateProcess() ) also works.

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