Linux中wait()和waitpid()函数怎么使用

   2025-02-15 5230
核心提示:在Linux中,wait()和waitpid()函数用于等待子进程的终止。wait()函数的原型如下:pid_t wait(int *status);其中status是一个指向

在Linux中,wait()waitpid()函数用于等待子进程的终止。

wait()函数的原型如下:

pid_t wait(int *status);

其中status是一个指向整型变量的指针,用于存储子进程的退出状态。该函数会阻塞调用进程,直到一个子进程终止。如果子进程已经终止,那么它的退出状态会被立即返回。如果调用进程没有子进程或者子进程已经被其他进程等待,那么wait()函数会立即出错返回-1。

waitpid()函数的原型如下:

pid_t waitpid(pid_t pid, int *status, int options);

其中pid是要等待的子进程的进程ID。使用-1表示等待任意子进程。status参数用于存储子进程的退出状态。options参数用于指定其他选项,如WNOHANG表示非阻塞等待。

waitpid()函数会阻塞调用进程,直到指定的子进程终止。如果指定的子进程已经终止,那么它的退出状态会被立即返回。如果调用进程没有指定的子进程或者指定的子进程已经被其他进程等待,那么waitpid()函数会立即出错返回-1。

以下是一个使用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("子进程开始运行\n");        sleep(3);        printf("子进程结束\n");        exit(0);    } else if (pid > 0) {        // 父进程        printf("父进程等待子进程终止\n");        wait(&status);        printf("子进程终止\n");    } else {        // fork失败        printf("fork失败\n");        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("子进程开始运行\n");        sleep(3);        printf("子进程结束\n");        exit(0);    } else if (pid > 0) {        // 父进程        printf("父进程等待子进程终止\n");        waitpid(pid, &status, 0);        printf("子进程终止\n");    } else {        // fork失败        printf("fork失败\n");        return 1;    }    return 0;}

以上示例中,父进程会等待子进程终止,然后打印相应的信息。

 
 
更多>同类维修知识
推荐图文
推荐维修知识
点击排行
网站首页  |  关于我们  |  联系方式  |  用户协议  |  隐私政策  |  网站留言