HiveBrain v1.2.0
Get Started
← Back to all entries
patterncppMinor

WIFEXITED combined with WIFSIGNALED

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
withcombinedwifexitedwifsignaled

Problem

I am testing the WIFEXITED to see if a child process exited abnormally or normally. According to documentation, it should return a non-zero status for a child process that terminated normally.

#include 
#include 
#include 
#include 

int main(int argc, const char* const* argv) {
    int *pointer=NULL;
    int status;
    pid_t pid=fork();
    if (pid==0) {
        std::cout 1) {
            std::cout << getpid() << "Going to crash myself" << std::endl;
            *pointer=1; //Segmentation fault as of null pointer dereference
        }
        else
            pointer=NULL; //Safe code
    }
    else {
        std::cout << "Parent is: " << getpid() << std::endl;
        pid_t terminated=waitpid(-1, &status, 0);
        std::cout << "Child " << terminated << " exited ";
        if (WIFEXITED(status)) std::cout << "GOOD";
        else {
             std::cout << "BAD";
             // Is it worth here to also check for WIFSIGNALED or is it redundant?
        }
        std::cout << std::endl;
    }
    std::cout << getpid() << " exiting normally" << std::endl;
    return 0;
}


To test a normal exit, call it without arguments, and an abnormal exit with segmentation fault, call it with some parameters.

Furthermore, if I use WIFSIGNALED it detects correctly the bad status, then, what's the use for WIFEXITED?

Is it advisable to use only WIFEXITED, or do you advise also to use WIFSIGNALED for further checks? Is this combination useful or redundant?

Solution

WIFSIGNALED / WIFSTOPPED

If you get into the "BAD" case, you may want to check whether WIFSIGNALED is true or WIFSTOPPED is true. WIFSIGNALED tells you if the program terminated with a signal (such as segv). WIFSTOPPED tells you if the program is currently stopped (but not terminated).

If your child process can never be stopped, then you can assume that it terminated abnormally and not bother checking those macros. In your particular example, your child will either segfault or exit right away, so it's unlikely that someone would be able to kill -STOP your process before it crashed.

Context

StackExchange Code Review Q#98993, answer score: 2

Revisions (0)

No revisions yet.