What is the purpose of wifexited in C++?

In C++, ‘wifexited’ is a macro used to check if a child process has exited normally. It is typically used in conjunction with the ‘waitpid’ system call.

The purpose of wifexited is to determine the exit status of a child process, to check if it exited normally without being interrupted by a signal or terminated due to any other exceptional circumstances. If the child process exited normally, wifexited will return a non-zero value.

Example of use:

#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <iostream>

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

    if (pid == 0) {
        // 子进程
        exit(123);
    } else {
        // 父进程
        int status;
        waitpid(pid, &status, 0);

        if (WIFEXITED(status)) {
            std::cout << "子进程以正常方式退出,退出状态码为: " << WEXITSTATUS(status) << std::endl;
        } else {
            std::cout << "子进程未以正常方式退出" << std::endl;
        }
    }

    return 0;
}

In the example above, the wifexited macro can be used to determine if the child process exited normally, and the wexitstatus macro can be used to retrieve the exit status code of the child process.

Please note that the wifexited macro only checks the status returned by waitpid, and cannot be used with the wait function.

Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds