zoukankan      html  css  js  c++  java
  • exit和wait一起可以彻底清除子进程的资源

    #include<stdio.h> 
    #include<unistd.h> 
    #include<sys/types.h> 
    #include<stdlib.h>
    #include <errno.h> 
    int main() 
    {
      pid_t p1,p2,pr; 
      int i; 
      for(i=0;i<=2;i++)
      { 
      if((p1=fork())==0)
      { 
      printf("parent process%d child  process%d
    ",getppid(),getpid()); 
      exit(0); //我发现把return 0替换为exit(0)也可以的!,不过编译器这两种的处理区别很大,以后再做解释
      }
      else{
      pr=wait(NULL);
    //如果成功,wait会返回被收集的子进程的进程ID,
    //如果调用进程没有子进程,调用就会失败,此时wait返回-1,同时errno被置为ECHILD。
      if( pr>0)  
       printf("I catched a child process with pid of %d
    ", pr); 
      else  
       printf("error: %s
    .
    ", strerror(errno)); 
      }
     }
     return 0;
    } 
    输出结果如下:
    parent process4595 child  process4596
    I catched a child process with pid of 4596
    parent process4595 child  process4597
    I catched a child process with pid of 4597
    parent process4595 child  process4598
    I catched a child process with pid of 4598
    当把exit注释后输出结果如下:
    parent process4642 child  process4643
    parent process4643 child  process4644
    parent process4644 child  process4645
    I catched a child process with pid of 4645
    I catched a child process with pid of 4644
    parent process4643 child  process4646
    I catched a child process with pid of 4646
    I catched a child process with pid of 4643
    parent process4642 child  process4647
    parent process4647 child  process4648
    I catched a child process with pid of 4648
    I catched a child process with pid of 4647
    parent process4642 child  process4649
    I catched a child process with pid of 4649
    //重新执行一边的结果
    parent process4657 child  process4658
    parent process4658 child  process4659
    parent process4659 child  process4660
    I catched a child process with pid of 4660
    I catched a child process with pid of 4659
    parent process4658 child  process4661
    I catched a child process with pid of 4661
    I catched a child process with pid of 4658
    parent process4657 child  process4662
    parent process4662 child  process4663
    I catched a child process with pid of 4663
    I catched a child process with pid of 4662
    parent process4657 child  process4664
    I catched a child process with pid of 4664
    从上面的输出结果可以得出:exit可以用来释放进程的资源,必须加上,当注释掉时,可能因为子进程的资源没有
    及时清理掉,所以导致wait阻塞住,不能及时清理掉子进程!
    总结:当进程发出exit该调用时,内核会释放进程占有的资源,释放进程上下文所占的内存空间,保留
    进程表项,将进程表项中记录进程状态的关键字设为僵死状态。内核在进程收到不可扑捉的信号时,会从内核内部调用exit
    ,使得进程退出。父进程通过wait,并释放进程表项。
     
  • 相关阅读:
    eclipse中的任务标记(TODO、FIXME、XXX)
    编码规范参考
    MVC,MVP 和 MVVM
    Android的两种事件处理机制
    在Eclipse中自定义类似syso的快捷代码模板
    Android
    eclipse使用tips-Toggle Mark Occurrences 颜色更改
    从 Eclipse 迁移至 Android Studio
    Java的位运算符详解实例——与(&)、非(~)、或(|)、异或(^)
    [POJ 2976]Dropping tests(0-1分数规划)
  • 原文地址:https://www.cnblogs.com/leijiangtao/p/4075706.html
Copyright © 2011-2022 走看看