我们可以在程序中调用CreateProcess(),创建一个进程,该函数会创建一个进程内核对象以及一个线程内核对象,并且将 其计数设为1,在该函数成功返回前,会将子进程的进程内核对象以及线程内核对象句柄拷贝到结构体中,因此,该函数成功返回后,进程内核对象与线程内核对象的计数都变为2,则后面的操作中应该减少引用计数,以保证内核对象正常释放,否则会造成内存的泄露,减少计数的时机根据需要而定,减少计数后,应该避免再去引用该句柄(可能失效)。
当我们创建一个进程之后,可以有3种方法让该进程退出,
1. 调用ExitProcess,该函数的原型如下:
This function ends a process and all of its threads.
VOID ExitProcess UINT uExitCode );
Parameters
-
uExitCode
-
[in] Specifies the exit code for the process and for all threads that are terminated as a result of this call.
To retrieve the process's exit value, use the GetExitCodeProcess function.
To retrieve a thread's exit value, use the GetExitCodeThread function.
Return Values
None.
2.调用函数TerminateProcess,该函数的原型如下:
This function terminates the specified process and all of its threads.
BOOL TerminateProcess( HANDLE hProcess, DWORD uExitCode );
Parameters
-
hProcess
- [in] Handle to the process to terminate. uExitCode
-
[in] Specifies the exit code for the process and for all threads terminated as a result of this call.
To retrieve the process's exit value, use the GetExitCodeProcess function.
To retrieve a thread's exit value, use the GetExitCodeThread function.
Return Values
Nonzero indicates success.
Zero indicates failure.
To get extended error information, call GetLastError.
3.进程的所有线程都退出。
对于前面2种情况,区别在于进程的任何线程都可以ExitProcess终止本进程,而TerminateProcess则可以让进程的任何线程终止本进程或者其它的进程。前者让进程优雅的退出,而后者略带强制意味,其区别在于,前者会通知进程加载的其它模块,进程要退出了,而后者则不会通知,有可能会错过一些清理过程,虽然一般情况下,都会释放内存,清理堆栈,释放对象,但是我们在一般情况下还是使用前者较好,只有在万不得已的情况下才使用后者。