在C语言中,wait()
函数用于让父进程等待子进程的结束。其语法如下:
#include#include pid_t wait(int *status);
wait()
函数会阻塞父进程,直到有一个子进程结束。在子进程结束后,父进程会继续执行。status
参数是一个指向整型变量的指针,用于获取子进程的退出状态。
下面是一个使用wait()
函数的例子:
#include#include #include #include #include int main() { pid_t pid = fork(); if (pid == -1) { perror("fork"); exit(1); } else if (pid == 0) { // 子进程 printf("Child process\n"); exit(0); } else { // 父进程 int status; wait(&status); printf("Parent process\n"); } return 0; }
在上面的例子中,首先通过fork()
函数创建了一个子进程。子进程会打印出"Child process",然后调用exit()
函数终止进程。父进程调用wait()
函数等待子进程结束,并获取子进程的退出状态。最后,父进程会打印出"Parent process"。
注意,wait()
函数还有其他用法,比如可以通过指定特定的子进程ID来等待特定的子进程结束。这里只是一个简单的示例,介绍了wait()
函数的基本用法。