[Linux服务器] linux之wait函数

1055 0
Honkers 2025-3-6 14:31:04 来自手机 | 显示全部楼层 |阅读模式

linux之wait函数
wait函数:成功:清理掉的子进程 ID;失败:-1 (没有子进程)
#include
#include
pid_t wait(int *wstatus);
wstatus是传出参数,
a.wait函数有3个功能:
(1)阻塞等待子进程退出
(2)回收子进程残留资源
(3)获取子进程结束状态(退出原因)。
b.可使用 wait 函数传出参数 status 来保存进程的退出状态。借助宏函数来进一步判断进程终止的具体原因。常用的宏函数可分为如下两组:
(1)WIFEXITED(status)为非0 -----------进程正常结束
如果宏函数WIFEXITED(status)的返回值为真(非0),则进一步调用宏函数WEXITSTATUS(status),此函数返回的是子进程退出的值,比如exit(10),返回值就是10
(2) WEXITSTATUS(status) 如上宏为真,使用此宏---------获取进程退出状态 (exit 的参数)
(3)WIFSIGNALED(status)为非0----------进程异常终止
如果宏函数WIFSIGNALED(status)的返回值为真(非0),则进一步调用宏函数WTERMSIG(status),此函数返回的是使子进程终止的那个信号的编号
(3) WTERMSIG(status) 如上宏为真,使用此宏----------取得使进程终止的那个信号的编号

wait函数的使用:wait.c

  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <unistd.h>
  4. #include <sys/types.h>
  5. #include <sys/wait.h>
  6. int main()
  7. {
  8. pid_t pid,wpid;
  9. int status;
  10. pid = fork();
  11. if(pid==0){
  12. //让子进程异常退出
  13. execl("abnor","abnor",NULL);
  14. printf("---child, my parent=%d, going to sleep 3s\n",getppid());
  15. sleep(60);
  16. printf("--------------child die--------------\n");
  17. //exit(76);
  18. return 100;
  19. }
  20. else if(pid>0){
  21. wpid = wait(&status);//子进程的退出状态保存在status中
  22. if(wpid==-1){
  23. perror("wait error:");
  24. exit(1);
  25. }
  26. //子进程正常退出
  27. if(WIFEXITED(status)){//如果宏函数WIFEXITED(status)的返回值为真,则继续调用宏函数WEXITSTATUS(status),此函数返回的是子进程退出的值
  28. printf("child exit with %d\n",WEXITSTATUS(status));
  29. }
  30. //子进程异常退出
  31. //测试子进程异常退出(不是子进程自己异常):运行程序之后,新开终端 ps aux ,杀掉子进程,此时会打印 child killed by ...
  32. if(WIFSIGNALED(status)){
  33. printf("chile killed by %d\n",WTERMSIG(status));
  34. }
  35. while(1){
  36. printf("I am paraent, pid = %d, myson = %d\n",getpid(),pid);
  37. sleep(1);
  38. }
  39. }
  40. else{
  41. perror("fork");
  42. return 1;
  43. }
  44. return 0;
  45. }
复制代码

结果:

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

×
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

中国红客联盟公众号

联系站长QQ:5520533

admin@chnhonker.com
Copyright © 2001-2026 Discuz Team. Powered by Discuz! X3.5 ( 粤ICP备13060014号 )|天天打卡 本站已运行