添加带有自定义标准错误的 fprintf() 语句后,标准输出挂起

Standard output hangs after adding fprintf() statement with custom standard error

本文关键字:语句 挂起 标准输出 fprintf 自定义 标准 错误 添加      更新时间:2023-10-16

我有一个C++类Archive,它有一个成员函数extractData()。此函数调用 realExtractData() ,后者在单独的 C 库中实现。

我想向 extractData() 函数传递一对通常stdoutstderrFILE * 实例,但我也想提供自定义文件指针的选项:

class Archive {
    public:
        ...
        int extractData(string id, FILE *customOut, FILE *customErr);
        ...
};
int
Archive::extractData(string id, FILE *customOut, FILE *customErr)
{
    if (realExtractData(id.c_str(), customOut) != EXIT_SUCCESS) {
        fprintf(stderr, "something went wrong...n");
        return EXIT_FAILURE;
    }
    return EXIT_SUCCESS;
}

如果我按所列方式调用上述内容,则将数据输出到标准输出没有延迟。所有提取的数据几乎立即发送到标准输出(stdout(:

FILE *outFp = stdout;
FILE *errFp = stderr;
Archive *archive = new Archive(inFilename);
if (archive->extractData(id, outFp, errFp) != EXIT_SUCCESS) {
    fprintf(errFp, "[error] - could not extract %sn", archive->getInFnCStr());
    return EXIT_FAILURE;
}

如果我更改extractData()以便其fprintf()调用使用 customErr

int
Archive::extractData(string id, FILE *customOut, FILE *customErr)
{
    if (realExtractData(id.c_str(), customOut) != EXIT_SUCCESS) {
        fprintf(customErr, "something went wrong...n");  /* <-- changed this line */
        return EXIT_FAILURE;
    }
    return EXIT_SUCCESS;
}

。然后,当我运行二进制文件时,二进制文件似乎挂起在处理输入并打印到标准输出中。

如果我fprintf()改回使用 stderr 而不是 customErr ,事情会再次正常工作,数据立即刷新到标准输出(我的customOut(。

这是缓冲问题吗?有没有办法解决这个问题?

"stderr and not customErr">

标准误差是未缓冲的,这意味着它几乎立即打印出来。 除非您使用低级操作系统调用,否则其他输出流将被缓冲,这意味着除非您使用 endl、::flush 或其他任何内容进行缓冲区刷新,否则它们将需要更长的时间来打印。

如果您想进行低级操作系统调用并且正在使用 unix,请查看以下内容:

http://www.annrich.com/cs590/notes/cs590_lecture_2.pdf

我还没有读过整本书,但是在扫描它时,它看起来好像与Unix中的Stevens Advanced Programming book具有类似的信息,该书对此进行了明确的讨论。