wait()函数说明
wait(等待子进程中断或结束,相关函数 waitpid,fork)
表头文件
#include<sys/types.h>
#include<sys/wait.h>
函数原型
pid_t wait (int * status);
函数说明
参数 status 是一个整形指针。如果status不是一个空指针,则终止进程的终止状态将存储在该指针所指向的内存单元中。如果不关心终止状态,可以将 status参数设置为NULL。
status 不是NULL时子进程的结束状态值会由参数 status 返回,而子进程的进程识别码作为函数返回值返回。
调用 wait 函数时,调用进程将会出现下面的情况:
如果其所有子进程都还在运行,则阻塞。
如果一个子进程已经终止,正等待父进程获取其终止状态,则获取该子进程的终止状态然后立即返回。
如果没有任何子进程,则立即出错返回。
(图源网络,侵删)
返回值
如果执行成功则返回子进程识别码(PID),如果有错误发生则返回-1。失败原因存于errno 中。
//fork()的使用方法,如果不进行wait()则当子进程退出时会出现子进程的内存无法释放的状态,因此子进程便成为了僵尸进程。
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
int main(){
pid_t pid;
printf("Start of fork testing\n");
pid = fork();
printf("Return of fork success:pid = %d\n",pid);
printf("father :%d %d",getpid(),getppid());
return 0;
}
//当没有子进程的时候,调用wait()的返回值是-1
#include <stdio.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <unistd.h>
int main(){
printf("wait return :%d",wait(NULL));
return 0;
}
运行结果:
wait return :-1
//一个wait(NULL)只能等待一个子进程结束,两个等待两个子进程
#include <stdio.h>
#include <sys/wait.h>
#include <unistd.h>
#include <sys/types.h>
int main(){
int pid;
printf("father progress,and father progress pid is %d\n",getpid());
if(0 == fork()){
printf("father progress forked,and child progress pid is %d\n",getpid());
}
else{
if(0