所谓进程等待,其实很简单。前面我们说过可以用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)
- {
- printf("This is child process, %d\n", getpid());
- sleep(5);
- }
- else
- {
- wait(NULL);
- printf("This is parent process, %d\n", getpid());
- }
- return 1;
- }
- [root@localhost fork]# ./fork
- This is child process, 2135
- This is parent process, 2134
本文介绍了如何在C++中使用wait函数使父进程等待子进程运行结束,并通过sleep函数验证这一过程。演示了在不同操作系统下(Linux与Windows)sleep函数参数的差异。
822

被折叠的 条评论
为什么被折叠?



