c - exit(1) 没有给我 1 作为退出值?

标签 c shell exit exit-code

为什么当我在 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 here enter image description here

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

我认为我的退出关闭了子进程,但主进程仍在继续..所以这就是为什么它给我主进程内部的返回值而不是退出进程的原因。

最佳答案

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

如果您希望 $? 成为子进程的退出值,则必须使用 wait() 来获取它,检索子进程的退出代码,然后然后退出你的主进程。

关于c - exit(1) 没有给我 1 作为退出值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60583761/

相关文章:

linux - 获取登录用户列表的脚本

java - 输入后退出Java程序

python - 退出 Python 函数调用

c - 在对包含 100 万个元素的数组进行排序时,如何找到合并排序算法崩溃的原因?

将 uint8_t 转换为二进制

c++ - C/C++中的主题挖掘算法

python - 捕获shell执行输出的简单python命令?

python - 将变量从 python 脚本传递到 bash 脚本

java - event.consume()之后如何退出EventHandler?

c - 如何避免在由 Eclipse 运行的 C 应用程序中出现不可复制的字符