exit(1)不会给我1作为退出值?

问题描述 投票:3回答:1

为什么当我在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;
}

我得到0作为返回值吗?

enter image description here

编辑:enter image description hereenter image description here

编辑:所以在这里我将main的返回值更改为5。我的函数的退出值高于42(idk为何如此)它给了我5作为输出..不知道发生了什么。我应该提到我在代码中使用fork()。也许是原因。enter image description here

我认为我的出口关闭了子进程,但是主进程继续运行。所以这就是为什么它给了我返回的值,而不是出口的值。

c shell exit exit-code
1个回答
5
投票

您的子进程以奇异值退出,但是您的主进程始终以0退出,这就是确定$?的原因。

如果要让$?作为子进程的退出值,则必须为wait(),获取子进程的退出代码,然后使用它退出主进程。

© www.soinside.com 2019 - 2024. All rights reserved.