How to get the return value of a program ran via calling a member of the exec family of functions?

Here is an example I wrote long time ago. Basically, after you fork a child process and you wait its exit status, you check the status using two Macros. WIFEXITED is used to check if the process exited normally, and WEXITSTATUS checks what the returned number is in case it returned normally:

#include <stdio.h>
#include <unistd.h>
#include <sys/wait.h>
int main()
{
    int number, statval;
    printf("%d: I'm the parent !\n", getpid());
    if(fork() == 0)
    {
        number = 10;
        printf("PID %d: exiting with number %d\n", getpid(), number);
        exit(number) ;
    }
    else
    {
        printf("PID %d: waiting for child\n", getpid());
        wait(&statval);
        if(WIFEXITED(statval))
            printf("Child's exit code %d\n", WEXITSTATUS(statval));
        else
            printf("Child did not terminate with exit\n");
    }
    return 0;
}

You can use waitpid to get the exit status of you child process as:

int childExitStatus;
waitpid( pID, &childExitStatus, 0); // where pID is the process ID of the child.

exec function familly does not return, the return int is here only when an error occurs at launch time (like not finding file to exec).

You have to catch return value from the signal sent to the process that forked before calling exec.

call wait() or waitpid() in your signal handler (well, you can also call wait() in your process without using any signal handler if it has nothing else to do).

Tags:

C

Exec