[英]How to NOT inherit stdin, stdout and stderr in CreateProcess() on Windows
CreateProcessW()
, accepts a flag bInheritHandles
. CreateProcessW()
,接受标志bInheritHandles
。 If it is set to FALSE
, only stdin
, stdout
and stderr
are inherited, the others are not.如果设置为FALSE
,则仅继承stdin
、 stdout
和stderr
,其他不继承。
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()
.在这种情况下,默认情况下不会继承stdin
、 stdout
和stderr
,但可以通过将它们包含在UpdateProcThreadAttribute()
的继承句柄中来继承它们。
That way, it is possible to inherit only stderr
for example.这样,例如可以仅继承stderr
。
But as a specific case, how to disable them all (including stdin
, stdout
and stderr
)?但作为一个具体案例,如何禁用它们(包括stdin
、 stdout
和stderr
)? UpdateProcThreadAttribute()
fails if we pass a NULL
/empty list for attribute PROC_THREAD_ATTRIBUTE_HANDLE_LIST
.如果我们为属性PROC_THREAD_ATTRIBUTE_HANDLE_LIST
传递NULL
/empty 列表,则UpdateProcThreadAttribute()
失败。
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.请注意,在这种情况下,我不想重定向stdin
、 stdout
和stderr
(我不想写入/读取它们),我只想禁用它们。
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.作为一种解决方法,可以创建一个虚拟HANDLE
并继承它,以便可以禁用stdin
、 stdout
和stderr
,但这有点笨拙。 bInheritHandles
set to FALSE
does not work because it enables stdin
, stdout
and stderr
. bInheritHandles
设置为FALSE
不起作用,因为它启用了stdin
、 stdout
和stderr
。 Passing DETACHED_PROCESS
might have other side effects (?).传递DETACHED_PROCESS
可能会产生其他副作用(?)。
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:哦,如果设置了STARTF_USESTDHANDLES
,并且如果bInheritHandles
设置为FALSE
,那么根本不会继承任何句柄,这正是我想要的:
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.编辑:或者,如此处所述,在dwCreationFlags dwCreationFlags
传递DETACHED_PROCESS
( CreateProcess()
的参数)也可以。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.