wait,waitpid学习测试

wait,waitpid学习测试

任务详情

1 用man wait, man waitpid学习wait waitpid的使用
2 写出wait 的测试代码,要能说明你理解了wait 的返回值的每一位的含义

实验步骤

1.用man wait, man waitpid学习wait waitpid的使用

使用man 2 wait可以看到函数原型,其中可以看到在2.6版本中新增叫了waitid()函数。
可以看到函数头文件:

#include <sys/types.h> /* 提供类型pid_t的定义 */
#include <sys/wait.h>

wait()函数功能:wait()函数使父进程暂停执行,直到它的一个子进程结束为止,该函数的返回值是终止运行的子进程的PID. 参数status所指向的变量存放子进程的退出码,即从子进程的main函数返回的值或子进程中exit()函数的参数。如果status不是一个空指针,状态信息将被写入它指向的变量。
waitpid函数功能:waitpid()的作用和wait()一样,但它并不一定要等待第一个终止的子进程,它还有若干选项,如可提供一个非阻塞版本的wait()功能等。实际上wait()函数只是waitpid()函数的一个特例。

2.写出wait 的测试代码,要能说明你理解了wait 的返回值的每一位的含义

宏定义描述:
WIFEXITED(wstatus):如果进程子进程正常结束,返回一个非零值
WEXITSTATUS(wstatus):返回子进程退出码;该值由状态参数的最低有效8位组成(仅当WIFEXITED返回值非零时该macro才会被调用)
WIFSIGNALED(wstatus):如果子进程被一个信号终止,则返回一个非零值
WTERMSIG(wstatus):返回终止这个子进程的信号码(仅当WIFSIGNALED返回值非零时该macro才能被调用)
WCOREDUMP(wstatus):如果这个子进程生成了一个核心转储(core dump),返回一个非零值(仅当WIFSIGNALED返回值非零时该macro才会被调用)
WIFSTOPPED(wstatus):如果子进程因接收一个信号暂停,返回一个非零值
WSTOPSIG(wstatus):返回这个暂停信号的信号码(仅当WIFSTOPPED返回值非零时该macro才会被调用)
WIFCONTINUED(wstatus):如果子进程因接收一个信号而恢复运行,则返回一个非零值

测试代码1:

#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <stdlib.h>
main()
{
        pid_t pc,pr;
        pc=fork();
 
       	if(pc<0) /* 如果出错 */
               printf("error ocurred!/n");
    	  else if(pc==0){ /* 如果是子进程 */
        	       printf("This is child process with pid of %d\n",getpid());
       		       sleep(10); /* 睡眠10秒钟 */
           		 }
     	   else{ /* 如果是父进程 */
              pr=wait(NULL); /* 在这里等待 */
              printf("I catched a child process with pid of %d\n",pr);
      	  } 
       exit(0);
}
测试代码2: ``` #include #include #include main() { int status; pid_t pc,pr;
    pc=fork();
    if(pc<0) /* 如果出错 */
           printf("error ocurred!\n");
    else if(pc==0){ /* 子进程 */
           printf("This is child process with pid of %d.\n",getpid());
           exit(3); /* 子进程返回3 */
    }
    else{ /* 父进程 */
           pr=wait(&status);
           if(WIFEXITED(status)){ /* 如果WIFEXITED返回非零值 */
                   printf("the child process %d exit normally.\n",pr);
                   printf("the return code is %d.\n",WEXITSTATUS(status));
           }else /* 如果WIFEXITED返回零 */
               printf("the child process %d exit abnormally.\n",pr);
    }

}

<img src="https://img2018.cnblogs.com/blog/1800808/201911/1800808-20191110140918842-1297064091.png" width="600" heigth="400"/>




posted @ 2019-11-10 14:14  蒋昕睿_20199307  阅读(273)  评论(0编辑  收藏  举报