wait和waitpid出现的原因
SIGCHLD
--当子进程退出的时候,内核会向父进程SIGCHLD信号,子进程的退出是个异步事件(子进程可以在父进程运行的任何时刻终止)
--子进程退出时,内核将子进程置为僵尸状态,这个进程成为僵尸进程,它只保留最小的一些内核数据结构,以便父进程查询子进程的退出状态
--父进程查询子进程的退出状态可以用wait/waitpid函数
wait获取staus后检测处理
宏定义 描述
WIFEXITED(status) 如果进程子进程正常结束,返回一个非零值
WEXITSTATUS(status) 如果WIFEXITED非零,返回子进程退出码
WIFSIGNALED(status) 子进程因为捕获信号而终止,返回非零值
WTERMSIG(status) 如果WIFSIGNALED非零,返回信号代码
WIFSTOPPED(status) 如果进程被暂停,返回一个非零值
WSTOPSIG(status) 如果WIFSTOPPED非零,返回信号代码
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/wait.h> int main(int arg,char *args[])
{
pid_t pid=fork();
if(pid==-)
{
printf("fork() failed ! error message:%s\n",strerror(errno));
return -;
}
if(pid>)
{
int status=;
printf("父进程\n");
wait(&status);
if(WIFEXITED(status))//WIFEXITED宏的释义: wait if exit ed
{
printf("子进程返回信息码:%d\n",WEXITSTATUS(status));
}else if(WIFSIGNALED(status))
{
printf("子进程信号中断返回信息码:%d\n",WTERMSIG(status));
}else if(WIFSTOPPED(status))
{
printf("子进程暂停返回信息码:%d\n",WSTOPSIG(status));
}else
{
printf("其他退出信息!\n");
}
}else if(pid==)
{
printf("i am child !\n");
abort();
//exit(100);
}
printf("game is over!\n");
return ;
}
wait()函数成功返回等待子进程的pid,失败返回-
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/wait.h> int main(int arg, char *args[])
{
pid_t pid = ;
int i = , ret = ;
for (i = ; i < ; i++)
{
pid = fork();
if (pid == -)
{
printf("fork() failed ! error message:%s\n", strerror(errno));
return -;
}
if (pid == )
{
printf("child haved run!\n");
exit();
}
}
while ()
{
//wait()函数的返回值是子进程的pid
ret = wait(NULL);
printf("子进程pid=%d\n", ret);
if (ret == -)
{
//父进程wait()函数阻塞过程中,有可能被别的信号中断,需要做异常处理
if (errno == EINTR)
{
continue;
}
break;
}
}
printf("game is over!\n");
return ;
}
waitpid
函数功能:用来等待某个特定进程的结束
函数原型:
pid_t waitpid(pid_t pid, int *status, int options);
参数:
status如果不为空,会把状态信息写到它指向的位置
options允许改变waitpid的行为,最有用的一个选项是WNOHANG,它的作用是防止waitpid把调用者的执行挂起
返回值:成功返回等待子进程的pid,失败返回-

最新文章

  1. Bloom Filter:海量数据的HashSet
  2. ubuntu samba server 配置多用户访问
  3. iOS有用的三方库
  4. Windows下解压版mysql的安装方法
  5. UDP打洞、P2P组网方式研究
  6. [INS-32025] 所选安装与指定 Oracle 主目录中已安装的软件冲突
  7. JavaBean中的get/set 的命名规范
  8. PHP Error 和 Logging 函数
  9. TCP及IP报头及协议
  10. nodeschool.io 5
  11. Dollars
  12. hdfs zkfc –formatZK 之HadoopIllegalArgumentException: Bad argument: –formatZK
  13. nginx多域名配置
  14. CentOS7.2上用KVM安装虚拟机window10踩过的坑
  15. YYHS-NOIP模拟赛-gcd
  16. CDN 机制
  17. hive中控制文件生产个数
  18. vue watch高级用法
  19. peizhiwenjian
  20. 企业内部在centos7.2系统中必杀技NTP时间服务器及内网服务器时间同步(windows和linux客户端同步)

热门文章

  1. 敏捷开发--scrum
  2. Nodejs之MEAN栈开发(九)---- 用户评论的增加/删除/修改
  3. 挖一挖C#中那些我们不常用的东西之系列(1)——ToDictionary,ToLookup
  4. 优化SQLServer&mdash;&mdash;表和分区索引(二)
  5. CentOS 6.2编译安装Nginx1.2.0+MySQL5.5.25+PHP5.3.13
  6. Java NIO 同步非阻塞
  7. Android应用程序“.R文件”消失怎么办
  8. python中strip,lstrip,rstrip简介
  9. cuda多线程间通信
  10. pitch yaw roll 的区别