Do I need to close handles to standard I/O after CreateProcess?

情到浓时终转凉″ 提交于 2019-12-11 09:55:37

问题


I use the following STARTUPINFO structure in my call to CreateProcess. Do I need to call CloseHandle on hStdError and hStdInput after the process ends?

startupInfo.cb = sizeof(startupInfo);
startupInfo.cb = sizeof(si);
startupInfo.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
startupInfo.hStdInput = GetStdHandle(STD_INPUT_HANDLE);
startupInfo.hStdOutput =  NULL;
startupInfo.hStdError = GetStdHandle(STD_ERROR_HANDLE);
startupInfo.wShowWindow = SW_HIDE;

回答1:


Since you didn't open those handles (that's not what GetStdHandle does), you don't need to close them (maybe you want to close them for some other reason, but it's unlikely). (Note: even if you did open the handles, you don't have to wait for the process to exit before you close them: once they are inherited, closing them in parent process has no effect on the child).

Note that hStdOutput should be INVALID_HANDLE_VALUE instead of NULL: that's the convention for passing the absence of a handle in STARTUPINFO.




回答2:


To the question "do you need to?" - the simple answer is "no". When a process ends all handles connected to it are destroyed in Windows OSs.. if you are creating a process within a process (I don't even want to try that in C, but it's quite simple in C#) then it would be safer to make sure the child process cleans up after itself before (or on-) termination.

A way to test this would be to try and access your handle after you've terminated your child process in your parent process.



来源:https://stackoverflow.com/questions/14729940/do-i-need-to-close-handles-to-standard-i-o-after-createprocess

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!