1.wait不带参数的使用
进程调用wait()后,就堵塞了自己,直到检测到当前进程的某个子进程已经退出。
如果坚持成功,则会返回该进程的ID。如果进程没有子进程,则会返回-1。
它是这样定义的。
#include<sys/types.h>
#include<sys/wait.h>
pid_t (int *status)
一般来说,如果我们不关心子进程如何退出,就设置parameter为null。
pid_t p1;
p1=wait(NULL);
或者:
int p1;
p1=wait(NULL);
其中pid_t 类型其实就是int 类型
我们来看看如下程序:
#include<sys/types.h>
#include<sys/wait.h>
#include<unistd.h>
#include<stdlib.h>
void main()
{
int p1;
pid_t p2;
p1=fork();
if(p1<0)
printf("error\n");
else if(p1==0)
{
printf("child process with pid of %d\n",getpid());
printf("p1=%d\n",p1);
sleep(5);
}
else
{
p2=wait(NULL);// 等待子进程消灭
printf("father process with pid of %d\n",getpid());
printf("child process with pid of %d\n",p2);
printf("child process with pid of %d\n",p1);
}
}
执行完后,我们发现结果如下:
在第1,第2行,显示后,隔了5秒的时间,才显示第3,4,5行
child process with pid of 4193
p1=0
father process with pid of 4192
child process with pid of 4193
child process with pid of 4193
我们还能得出如下结论:
P1=fork(),在子进程中,P1的值为0,在父进程中,P1的值为子进程的进程ID
也就是说
fork的返回值,在子进程中为0,父进程中为子进程的ID
==
2.wait带参数status的使用
如果status的值不为null,则wait()函数会把子进程退出时的状态值存入其中。比如,子进程调用exit(0),那么这个状态值就是0.
函数代码如下:
int status;
pid_t p1;
p1=wait(& status);
其中涉及到2个常用的宏如下
WIFEXITED(status) ,表示如果子进程正常退出,返回非0值
WEXITSTATUS(status), 在WIFEXITED(status)的返回值为非0的情况下,该宏返回子进程的状态值
#include<sys/wait.h>
#include<sys/types.h>
#include<unistd.h>
#include<stdlib.h>
void main()
{
pid_t p1,p2;
int status;
p1=fork();
if(p1<0)
printf("error\n");
else if(p1==0)
{
printf("the child process with pid of %d\n",getpid());
exit(6);
}
else
{
p2=wait(&status);//参数为status
if(WIFEXITED(status)) //WIFEXITED(status)返回值非0
{
printf("the child process %d exit normally,and its status is %d\n",p1,WEXITSTATUS(status));
}
else printf("the child process %d exit abnormally",p2);
}
}
the child process with pid of 4413
the child process 4413 exit normally,and its status is 6