Home > Net >  Get return code of a child process created with fork()
Get return code of a child process created with fork()

Time:09-30

I'm trying to get the return code of the child process created by fork(). I'm using wait() function to get the return code. Everything is working fine but the return values given by wait() is 256 times the actual return value. Can anybody explain why is that.

Code:

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

constexpr int PROCESS_COUNT = 7;

int main() {
    pid_t pid;
    
    for (int i = 0; i < PROCESS_COUNT; i  ) {
        pid = fork();
        if (pid > 0) {
            int returnCode;
            int pid;

            pid = wait(&returnCode);
            std::cout << "\n Process: " << pid << "; i: " << i
                << "; Return Code: " << returnCode << std::endl;
        }
        else {
            return i;
        }
    }

    return EXIT_SUCCESS;
}

Output:


 Process: 7910; i: 0; Return Code: 0

 Process: 7911; i: 1; Return Code: 256

 Process: 7912; i: 2; Return Code: 512

 Process: 7913; i: 3; Return Code: 768

 Process: 7914; i: 4; Return Code: 1024

 Process: 7915; i: 5; Return Code: 1280

 Process: 7916; i: 6; Return Code: 1536

CodePudding user response:

Please read the wait manual page. The value given by wait doesn't only contain the child-process exit code, but also other flags and values.

To get the exit status you first need to make sure that the child-process really exited the normal way. This is done with the WIFEXITED macro.

Then to get the actual status use the WEXITSTATUS macro.

Something like this:

pid_t pid = wait(&returnCode);
if (pid >= 0 && WIFEXITED(returnCode))
{
    std::cout << "Child process " << pid << " exited normally with return code " << WEXITSTATUS(returnCode) << '\n';
}

Note that I added the "correct" type actually returned by wait, and that I also check it to make sure that wait didn't fail.

  • Related