yxq_bd吧 关注:36贴子:1,793
  • 2回复贴,共1

关于判断一个进程已经结束退出

只看楼主收藏回复

  很简单的一个问题,不是么。1F还是空着的好


1楼2012-06-18 01:09回复
      来自msdn#microsoft*com/en-us/library/ms686722(v=vs.85)#aspx,Terminating a Process
    Terminating a process has the following results:
    ·Any remaining threads in the process are marked for termination.
    ·Any resources allocated by the process are freed.
    ·All kernel objects are closed.
    ·The process code is removed from memory.
    ·The process exit code is set.
    ·The process object is signaled.
      While open handles to kernel objects are closed automatically when a process terminates, the objects themselves exist until all open handles to them are closed. Therefore, an object will remain valid after a process that is using it terminates if another process has an open handle to it.
      The GetExitCodeProcess function returns the termination status of a process. While a process is executing, its termination status is STILL_ACTIVE. When a process terminates, its termination status changes from STILL_ACTIVE to the exit code of the process.
      When a process terminates, the state of the process object becomes signaled, releasing any threads that had been waiting for the process to terminate. For more about synchronization, see Synchronizing Execution of Multiple Threads.
      后面的略。
      简要说一下,就是,一个进程启动时,操作系统生成一个内核对象(kernel object)来管理其运行,其他进程可以通过与这个对象连接(通过open handle)来获取该进程的信息并与之交互。而当该进程结束后,如果仍有其他进程与该内核对象保持连接,则该对象将继续存在并可访问,直到所有的连接被关闭(close)。
      进程结束后,其内核对象可以由于被连接而继续存在,并反映出进程已结束的状态,包括:使用GetExitCodeProcess函数可以取得的,进程的返回值,若进程没有结束则该值是一个命名常量STILL_ACTIVE;这个进程内核对象将处于信号状态(signaled),可以被WaitFor系列函数发现。
    


    2楼2012-06-18 01:35
    回复
        可见,GetExitCodeProcess函数可以用来判断进程已经结束,但是存在一个严重缺陷,它无法判断进程正在运行。因为STILL_ACTIVE是一个命名常量,不管它被定为多少(这里是259),总有遇到撞车的程序的一天,比如一个程序用0到1000或者更大的返回值表示退出时的某种数量,当返回值恰好为STILL_ACTIVE定义的值时,这一方法就会无法判断或者发生误判。
       这个函数更适合用于在已知进程结束后取返回值而不是用于判断进程是否已经结束,当然出现STILL_ACTIVE以外的值的话确实可以确认结束了,而STILL_ACTIVE仅仅是一种异常处理,即提示有可能进程并没有结束,需要另行判断进程是否确已结束。
        那么,WaitForSingleObject函数呢,真是一个很受误解的函数名字啊。关于等待系函数的一个误解是,如果信号发出时我们没有处于等待状态,是不是就错过信号了呢?这种情况确实存在,如果等待的是瞬间发出的消息的话。但是进程结束后,进程内核对象是处于信号状态,只要我们没有断开连接(close handle,这样内核对象有可能被删除),就可以随时用这个函数发现其信号状态。
       这是一个等待系函数,会使线程进入等待状态而不继续执行直到等待的进程结束为止,这与我们判断进程是否已经结束并根据判断的结果执行相应的任务的需要不符,吧。不是的哦,等待是可以限定时间过时不候的,如参数说明所说,如果等待超时为0,那么线程根本不会进入等待状态(而不是进入等待后最速返回),而恰恰适合用于进行瞬时状态判断。


      6楼2012-06-18 14:01
      回复