richard.g
richard.g

Reputation: 3765

the return value of a child process

I am new to fork and exec, and I tried the following program.

Program 1:

int main(int argc, char *argv[]){
    pid_t pid;
    int status;
    pid = fork();
    if(pid == 0){
        printf("new process");
        execv("p1",argv);
        }
    else{
        pid_t pr = wait(&status);// I am trying to get the exit value
                                //  of the sub process.
        printf("the child process exit with %d",status);
        printf("father still running\n");
    }
}

Program 2:

int main(){
    std::cout<<"I am the new thread"<<std::endl;
    sleep(1);
    std::cout<<"after 1 second"<<std::endl;
    exit(1); 
}

I run the first program, and the output is "the child process exit with 256". Why is the result 256 instead of 1? If I change exit(1) to exit(2), the result becomes 512, why is that? It only worked if I return 0.

Upvotes: 1

Views: 973

Answers (1)

paxdiablo
paxdiablo

Reputation: 881113

The status value you get back from the wait system call is not necessarily what your child process exited with.

There are a number of other pieces of information that can be returned as well, such as:

  • did the process terminate normally?
  • was it terminated by a signal?
  • what was the signal that terminated it?
  • did it dump core?

In order to extract the exit code, you use a macro:

WEXITSTATUS(status)

That, and the macros that can give you more information, should be available on the wait man-page, such as the one here.

Upvotes: 3

Related Questions