温馨提示×

wifexited和waitpid函数怎样配合

小樊
82
2024-07-04 06:46:19
栏目: 编程语言

wifexited和waitpid函数可以一起使用来等待子进程的退出状态,并且获取子进程的退出状态信息。

具体步骤如下:

  1. 使用fork函数创建子进程
  2. 在父进程中使用waitpid函数来等待子进程的退出状态
  3. 在waitpid函数中传入WIFEXITED选项来检查子进程是否正常退出
  4. 使用WEXITSTATUS宏来获取子进程的退出状态信息

示例代码如下:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>

int main() {
    pid_t pid = fork();

    if (pid < 0) {
        perror("fork error");
        exit(-1);
    } else if (pid == 0) {
        // 子进程
        printf("Child process is running\n");
        exit(0);
    } else {
        // 父进程
        int status;
        waitpid(pid, &status, 0);

        if (WIFEXITED(status)) {
            printf("Child process exited normally with status: %d\n", WEXITSTATUS(status));
        }
    }

    return 0;
}

在上面的示例代码中,父进程通过waitpid函数等待子进程的退出状态,并通过WIFEXITED和WEXITSTATUS来获取子进程的退出状态信息。

0