Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do I need to use CloseHandle after creating a new process?

I need to launch a separate process/application from a context menu; I'm using the function launch_program to do so. I don't care about the exit code from the created process once it terminates, I just want to be able to launch it. My question is: if the variables startup_info and proc_info are being passed by reference to CreateProcess am I able to use CloseHandle on them if I'm just going to return from the function to my Main Thread?

void launch_program()
{
    STARTUPINFO startup_info;
    PROCESS_INFORMATION proc_info;
    LPCSTR location = "C:\\Program Files (x86)\\Internet Explorer\\iexplore.exe";

    ZeroMemory( &startup_info,sizeof(startup_info));
    startup_info.cb = sizeof(startup_info);
    ZeroMemory( &proc_info,sizeof(proc_info));

    CreateProcess(  location,
                    NULL,
                    NULL,
                    NULL,
                    FALSE,
                    0,
                    NULL,
                    NULL,
                    &startup_info,
                    &proc_info);

}

I used https://msdn.microsoft.com/en-us/library/windows/desktop/ms682512(v=vs.85).aspx for reference.

PS I just used Internet Explorer as a filler
[EDIT] For Completeness:

CloseHandle(proc_info.hProcess);
CloseHandle(proc_info.hThread);
like image 842
pixel Avatar asked Jul 07 '16 02:07

pixel


1 Answers

Yes, you can and should close those handles when you no longer need them, including right away if you'll never need them.

From the page you linked Creating Processes:

The thread and process handles are created with full access rights, although access can be restricted if you specify security descriptors. When you no longer need these handles, close them by using the CloseHandle function.


[ EDIT ] To emphasize the *should* close part, which maybe isn't stated strongly enough in the docs, here is a quote from @RaymondChen's blog:

Why do some process stay in Task Manager after they’ve been killed?

After all the drivers have acknowledged the death of the process, the "meat" of the process finally goes away. All that remains is the "process object", which lingers until all handles to the process and all the threads in the process have been closed. (You did remember to CloseHandle the handles returned in the PROCESS_INFORMATION structure that you passed to the CreateProcess function, didn't you?)

like image 87
dxiv Avatar answered Nov 20 '22 17:11

dxiv