wait()函数
所需头文件:#include <sys/types.h> #include<sys/wait.h>
函数原型:pid_t wait(int *status)
作用:wait()
函数会暂停当前进程的执行,直到有子进程的结束,此时wait()
函数会返回子进程结束状态值,由status
接收,如果对这个子进程是如何结束的并不关心,那么这个参数也可以设为NULL。如果执行成功会返回子进程的PID,有错返回-1。
例子:
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
int main()
{
pid_t pid;
pid = fork();
if(pid == (pid_t)0) //如果是子进程
{
printf("this is the child process!\n");
sleep(5); //等待5秒
}
else
{
wait(NULL);
printf("this is the father process!\n");
}
return 0;
}
输出结果:
this is the child process!
this is the father process!
运行这段代码会得到这样的结果,但是可以发现,第二个输出this is the father process!
,会等待5秒再输出。这是因为wait()
函数会等待子进程的结束当前进程再继续进行,否则当前进程一直处于堵塞状态。当我们调用fork()
函数,成功地拷贝出来另一个子进程时,父子进程会各自完成各自的代码,当父进程遇到wait()
函数时,会处于堵塞状态,等待子进程的结束才继续向下执行。
waitpid()函数
所需头文件:#include <sys/types.h> #include <sys/wait.h>
函数原型:pid_t waitpid(pid_t pid, int *status, int options)
作用: 作用和wait()
函数类似,只是多了两个参数pid
和options
,pid
参数的含义是传入想要等待结束的子进程识别码,options
参数可以进行一些特殊的处理,可以填0表示没有选项,多个选项之间可以用或(|
)隔开。如果执行成功则返回子进程的PID, 如果有错误发生则返回-1,另外如果设置了WNOHANG
参数,没有结束的子进程的话就返回0。
有以下这4种pid:
- pid<-1 等待指定进程组ID为pid的绝对值的任何子进程.
- pid=-1 等待任何子进程, 相当于wait().
- pid=0 等待同一进程组的任何子进程.
- pid>0 等待任何子进程识别码为pid 的子进程,比如传进去的pid值是3000,那么只有当pid值为3000的子进程结束了,当前进程才能继续执行
有以下8种options:
- WNOHANG:如果没有任何已经结束的子进程则马上返回, 不予以等待.
- WUNTRACED:如果子进程进入暂停执行情况则马上返回, 但结束状态不予以理会.
- WIFEXITED(status):如果子进程正常结束则赋值为非0值.
- WEXITSTATUS(status):取得子进程exit()返回的结束代码, 一般会先用WIFEXITED 来判断是否正常结束才能使用此宏.
- WIFSIGNALED(status):如果子进程是因为信号而结束则此宏值为真
- WTERMSIG(status):取得子进程因信号而中止的信号代码, 一般会先用WIFSIGNALED 来判断后才使用此宏.
- WIFSTOPPED(status):如果子进程处于暂停执行情况则此宏值为真. 一般只有使用WUNTRACED时才会有此情况.
- WSTOPSIG(status):取得引发子进程暂停的信号代码, 一般会先用WIFSTOPPED 来判断后才使用此宏.
例子:
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
int main()
{
pid_t pid;
pid = fork();
if(pid == (pid_t)0) //如果是子进程
{
printf("this is the child process!\n");
sleep(5);
}
else
{
int temp = 0;
while(temp==0) //除非子进程结束,否则一直循环
{
if((temp = waitpid(pid, NULL, WNOHANG))!=0) //只有当子进程结束时,返回值才不为0
printf("this is the father process!\n");
else
printf("the child process is not exited\n");
}
}
return 0;
}
输出结果:
this is the child process!
the child process is not exited
the child process is not exited
the child process is not exited
..... //这里有很多个输出,省略了
the child process is not exited
the child process is not exited
the child process is not exited
this is the father process!
可见我们设置了WNOHANG
参数时,每次父进程执行waitpid()
函数,发现子进程没结束,不用等待子进程结束而继续执行,此时返回值为0,继续执行循环,直到子进程结束。其它参数感兴趣的可以自己试一试。