linux进程控制——进程等待——wait、waitpid
warning:
这篇文章距离上次修改已过180天,其中的内容可能已经有所变动。
在Linux中,wait()
和waitpid()
系统调用用于控制进程的执行流程,使父进程等待一个特定的子进程结束。
wait()
函数:
wait()
函数用于等待任何一个子进程结束。当调用wait()
函数时,父进程会进入休眠状态,直到它的一个子进程结束。
#include <sys/types.h>
#include <sys/wait.h>
pid_t wait(int *status);
waitpid()
函数:
waitpid()
函数提供了更多的控制选项。它可以等待特定的进程,也可以不等待进程。
#include <sys/types.h>
#include <sys/wait.h>
pid_t waitpid(pid_t pid, int *status, int options);
在waitpid()
函数中,pid
参数指定了要等待的进程ID。如果pid
大于0,那么就会等待ID与pid
相等的子进程。如果pid
等于-1,那么就会等待任何一个子进程。status
参数是一个输出参数,用于获取子进程结束时的状态。options
参数可以控制行为,如WNOHANG
,如果没有子进程结束,那么waitpid()
函数会立即返回,不会阻塞父进程。
解决方案:
以下是使用wait()
和waitpid()
函数的示例代码。
- 使用
wait()
函数的示例:
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
int main() {
pid_t pid = fork();
if (pid == -1) {
perror("fork failed");
exit(EXIT_FAILURE);
}
if (pid == 0) {
// Child process
printf("Child PID: %d\n", getpid());
sleep(10);
printf("Child is done\n");
exit(EXIT_SUCCESS);
} else {
// Parent process
int status;
pid_t wpid = wait(&status);
if (wpid == -1) {
perror("wait failed");
exit(EXIT_FAILURE);
}
printf("Parent: Child has finished\n");
}
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 = fork();
if (pid == -1) {
perror("fork failed");
exit(EXIT_FAILURE);
}
if (pid == 0) {
// Child process
printf("Child PID: %d\n", getpid());
sleep(10);
printf("Child is done\n");
exit(EXIT_SUCCESS);
} else {
// Parent process
int status;
pid_t wpid =
评论已关闭