【问题标题】:exit(1) does not give me 1 as an exit value?exit(1) 不给我 1 作为退出值?
【发布时间】:2020-03-08 01:30:00
【问题描述】:

为什么当我在 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 作为返回值?

编辑:

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

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

【问题讨论】:

  • 当您使用另一个较小的值时,它是否有效?说,exit(42)?
  • 操作系统是什么?
  • 您显示的代码应该可以工作。要么发生了其他事情(显示整个代码),要么你的 shell 不是标准的。
  • EXIT_FAILURE 实际上是正确的、可移植的方式。该值是实现定义的。在这种情况下,1 可能是预期的,但它可能会在另一个平台上编译成其他东西。 (例如,在 OpenVMS 上 1 实际上是成功而不是失败。)
  • 我尝试了退出 (42),但它仍然为我的回声打印 0。 @usr2564301

标签: c shell exit exit-code


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-01-12
    • 2020-01-16
    • 2022-07-21
    • 1970-01-01
    • 2019-01-25
    • 1970-01-01
    • 2015-05-11
    • 2014-05-13
    相关资源
    最近更新 更多