在CentOS7中运行C程序,遇到errno 9(Bad file Descriptor)怎么办?

czg*_*czg 1 c fopen errno

在下面的代码中,我将打开一个文件并写入一些内容。
由于程序是在多个线程上并发运行的,因此fopen函数执行完毕后log_fd 的值可能为NULL。 然后,程序崩溃并退出。

static void __log_prt__(const char *fmt, va_list ap)
{   
    // omitted code ...

    FILE *log_fd = fopen(def_log_file, "a");

    // omitted code ...

    fclose(log_fd);
}
Run Code Online (Sandbox Code Playgroud)

这会导致errno 9: Bad file detector
我修改了程序,循环遍历fopen函数,直到它的返回值不再为 NULL,就像下面的代码:

static void __log_prt__(const char *fmt, va_list ap)
{   
    // omitted code ...

    FILE *log_fd = fopen(def_log_file, "a");
    while (log_fd == NULL) {
        log_fd = fopen(def_log_file, "a");
    }

    // omitted code ...

    fclose(log_fd);
}
Run Code Online (Sandbox Code Playgroud)

这样程序就不会再出现errno 9导致的崩溃了。
现在我有一个问题,这样做正确吗?有没有更合理的方法呢?

Har*_*ith 5

FILE *log_fd = fopen(def_log_file, "a");\n    while (log_fd == NULL) {\n        log_fd = fopen(def_log_file, "a");\n    }\n
Run Code Online (Sandbox Code Playgroud)\n

这种做法看起来非常乐观。从手册页中,我统计了大约 42 种可能导致fopen ()失败的不同错误条件。\xc2\xb9

\n

如果fopen ()返回NULL,则不能保证召回它会神奇地修复最初导致其失败的条件。

\n

记住:

\n
    \n
  • 失败永远是一种选择。
  • \n
  • 快速失败、早期失败、经常失败。
  • \n
  • 并且不要以安全为代价换取任何东西。
  • \n
\n

[1] \xe2\x80\x94 其中包括ENOMEM(错误无内存),此时您应该中止。

\n