Search code examples
cshellexit-code

Accessing exit codes from a c program


I have tried to find solution all over the internate, but forums keep saying it is impossible, so here I a with my question. How does a shell (any shell like bash) keep track of exit codes. Is it by tracking their child process? (if so how could I go about implementing such a thing in a program where I am creating and killing many children processes) Or Is there a global variable that is equivalent to $? that I can access in c? Or do they store it in a file?


Solution

  • Here is an example of executing grep on a path that doesn't exist and getting the return code in the parent:

    code:

    #include <errno.h>
    #include <sys/wait.h>
    #include <stdio.h>
    #include <unistd.h>
    
    
    int main(int argc, char* argv[]) {
    
        pid_t childPid;
        switch(childPid = fork()) {
        case -1:
            fprintf(stderr, "Error forking");
            return 1;
        case 0:
            printf("CHILD: my pid is: %d\n", getpid());
            int ret = execlp(argv[1], argv[1], argv[2], argv[3], (char *) NULL);
            if (ret == -1) {
                printf("CHILD: execv returned: %d\n", errno);
                return errno;
            }
            break;
        default:
            printf("I am the parent with a child: %d\n", childPid);
            int childRet;
            wait(&childRet);
            printf("PARENT, child returned: %d\n", childRet >> 8);
        }
        return 0;
    }
     
    

    Execution:

    # Example of Failure execution:
    
    [ttucker@zim c]$ cc -o stackoverflow so.c && ./stackoverflow grep test /does/not/exists
    I am the parent with a child: 166781
    CHILD: my pid is: 166781
    grep: /does/not/exists: No such file or directory
    PARENT, child returned: 2
    
    # Example of a successful execution:
    
    [ttucker@zim c]$ cc -o stackoverflow so.c && ./stackoverflow echo foo bar
    I am the parent with a child: 166809
    CHILD: my pid is: 166809
    foo bar
    PARENT, child returned: 0