Normally, you do not do anything special to end a process, just as you do not do anything to end a thread. When a thread reaches the return instruction at the end of its startup procedure, the system calls ExitThread and the thread terminates, leaving an exit code behind. When the primary thread in a process comes to the end of its starting procedure (usually WinMain), the system implicitly calls ExitProcess instead of ExitThread. ExitProcess forces all the threads in a process to end, no matter what they may be doing at the time. Any thread, however, may call ExitProcess explicitly to end its process at any time.
void ExitProcess( UINT fuExitCode );
You define the exit code to be whatever you like. Like threads, processes remain in memory even after they terminate, only dying when all the handles to them are closed. To determine a process’s exit code, keep its handle and call GetExitCodeProcess.
BOOL GetExitCodeProcess(
HANDLE hProcess, // handle to the process
LPDWORD lpdwExitCode ); // buffer to receive exit code
If the process has not ended, GetExitCodeProcess reports the exit code as STILL_ACTIVE.
Normally, a process ends when its primary thread ends. The primary thread may, however, choose to quit without ending the process. If the primary thread ends with an explicit call to ExitThread, the system does not call ExitProcess. Other threads in the process continue to execute, and the process runs until any thread calls ExitProcess directly or until the last thread ends.
A number of things happen when a process ends:
Note that when a parent process dies, it does not take its children with it. The children, if there are any, continue to run independently.
Another command, TerminateProcess, also forces a process to exit. Actually this command brings the process to an abrupt and crashing halt, preventing some of the usual cleanup from happening. DLLs, for example, are not notified when TerminateProcess kills one of their clients. Like TerminateThread, TerminateProcess is abrupt, messy, and best avoided whenever possible.
BOOL TerminateProcess(
HANDLE hProcess, // handle to the process
UINT fuExitCode ); // exit code for the process