Linux中wait()和waitpid()函数如何使用
在Linux中,wait()
和waitpid()
函数用于等待子进程的终止。
wait()
函数的原型以下:
pid_t wait(int *status);
其中status
是一个指向整型变量的指针,用于存储子进程的退出状态。该函数会阻塞调用进程,直到一个子进程终止。如果子进程已终止,那末它的退出状态会被立即返回。如果调用进程没有子进程还是子进程已被其他进程等待,那末wait()
函数会立即出错返回⑴。
waitpid()
函数的原型以下:
pid_t waitpid(pid_t pid, int *status, int options);
其中pid
是要等待的子进程的进程ID。使用⑴
表示等待任意子进程。status
参数用于存储子进程的退出状态。options
参数用于指定其他选项,如WNOHANG
表示非阻塞等待。
waitpid()
函数会阻塞调用进程,直到指定的子进程终止。如果指定的子进程已终止,那末它的退出状态会被立即返回。如果调用进程没有指定的子进程还是指定的子进程已被其他进程等待,那末waitpid()
函数会立即出错返回⑴。
以下是一个使用wait()
函数的示例:
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
int main() {
pid_t pid;
int status;
pid = fork();
if (pid == 0) {
// 子进程
printf("子进程开始运行
");
sleep(3);
printf("子进程结束
");
exit(0);
} else if (pid > 0) {
// 父进程
printf("父进程等待子进程终止
");
wait(&status);
printf("子进程终止
");
} else {
// fork失败
printf("fork失败
");
return 1;
}
return 0;
}
以下是一个使用waitpid()
函数的示例:
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
int main() {
pid_t pid;
int status;
pid = fork();
if (pid == 0) {
// 子进程
printf("子进程开始运行
");
sleep(3);
printf("子进程结束
");
exit(0);
} else if (pid > 0) {
// 父进程
printf("父进程等待子进程终止
");
waitpid(pid, &status, 0);
printf("子进程终止
");
} else {
// fork失败
printf("fork失败
");
return 1;
}
return 0;
}
以上示例中,父进程会等待子进程终止,然后打印相应的信息。
TOP