所谓进程等待,其实很简单。前面我们说过可以用fork创建子进程,那么这里我们就可以使用wait函数让父进程等待子进程运行结束后才开始运行。注意,为了证明父进程确实是等待子进程运行结束后才继续运行的,我们使用了sleep函数。但是,在linux下面,sleep函数的参数是秒,而windows下面sleep的函数参数是毫秒。
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main(int argc, char* argv[])
{
pid_t pid;
pid = fork();
if(0 == pid)
{
sleep(5);
printf("This is child process, %d\n", getpid());
}
else
{
wait(NULL);
printf("This is parent process, %d\n", getpid());
}
return 1;
}