进程的创建以及退出

130 篇文章 0 订阅
123 篇文章 1 订阅

    我们可以在程序中调用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则可以让进程的任何线程终止本进程或者其它的进程。前者让进程优雅的退出,而后者略带强制意味,其区别在于,前者会通知进程加载的其它模块,进程要退出了,而后者则不会通知,有可能会错过一些清理过程,虽然一般情况下,都会释放内存,清理堆栈,释放对象,但是我们在一般情况下还是使用前者较好,只有在万不得已的情况下才使用后者。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值