Search code examples
cshellexitexit-code

exit(1) does not give me 1 as an exit value?


Why when i execute this code inside a function in c

int Pandoc(char *file)
{

    //printf("Pandoc is trying to convert the file...\n");

    // Forking
    pid_t pid;
    pid = fork();

    if (pid == -1)
    {
        perror("Fork Error");
    }
    // child process because return value zero
    else if (pid == 0)
    {

        //printf("Hello from Child!\n");
        // Pandoc will run here.

        //calling pandoc
        // argv array for: ls -l
        // Just like in main, the argv array must be NULL terminated.
        // try to run ./a.out -x -y, it will work
        char *output = replaceWord(file, ".md", ".html");
        //checking if the file exists

        char *ls_args[] = {"pandoc", file, "-o", output, NULL};
        //                    ^
        //  use the name ls
        //  rather than the
        //  path to /bin/ls

        // Little explaination
        // The primary difference between execv and execvp is that with execv you have to provide the full path to the binary file (i.e., the program).
        // With execvp, you do not need to specify the full path because execvp will search the local environment variable PATH for the executable.
        if(file_exist(output)){execvp(ls_args[0], ls_args);}
        else
        {
            //Error Handeler
            fprintf(stdout, "pandoc should failed with exit 42\n");
            exit(42);
            printf( "hello\n");
        }
    }
    return 0;
}

I get 0 as a returned value?

enter image description here

EDIT: enter image description here enter image description here

Edit: So here i changed the return value of the main to 5. The exit value for my function above to 42 (idk why tho) It gives me 5 as an output.. no idea whats hapening. I shouldve mentionned that i use fork() in my code.. Maybe its the reason. enter image description here

I think that my exit shut off the child process but the main continiues.. so thats why its giving me the returned value inside of my main and not the exit one.


Solution

  • Your child process exits with an exotic value, but your main process always exits with 0, and that's what determines $?.

    If you want $? to be the exit value of the child process, you'll have to wait() for it, retrieve the child's exit code, and then exit your main process with it.