添加带有自定义标准错误的 fprintf() 语句后,标准输出挂起
Standard output hangs after adding fprintf() statement with custom standard error
我有一个C++类Archive
,它有一个成员函数extractData()
。此函数调用 realExtractData()
,后者在单独的 C 库中实现。
我想向 extractData()
函数传递一对通常stdout
和stderr
的 FILE *
实例,但我也想提供自定义文件指针的选项:
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具有类似的信息,该书对此进行了明确的讨论。
相关文章:
- 挂起和取消挂起一个文件DLL
- 如何防止C++遗留代码中的挂起指针
- 为什么所有C++编译器都会崩溃或挂起此代码
- 我编写了代码将十进制分数转换为其二进制等效数.它编译得很好,但在执行时挂起
- 为什么我的 if else 语句不起作用并从数组中输出正确的索引?
- 构建挂起,即使是适度的文件大小
- 循环挂起迭代的 std::擦除 on std::list
- Poco::Net::FTPClientSession 在 open() 方法上挂起 129 秒,如果 ftp 主机不存
- Node.js fs.open() 在尝试打开 4 个以上的命名管道 (FIFO) 后挂起
- 从不同进程中的另一个线程挂起/恢复线程或进程
- Boost (Beast) websocket:同步写入挂起
- 为什么析构函数挂起
- 使用互斥会挂起程序
- 在C++和 Python 程序中使用命名管道的 IPC 挂起
- 设置变量时C++程序挂起
- 第一次尝试使用new动态创建结构数组,程序挂起没有错误
- 从stdin读取时子进程挂起(fork/dup2竞争条件)
- 有时ShowWindow从不调用OnShowWindow,主应用程序挂起
- 添加带有自定义标准错误的 fprintf() 语句后,标准输出挂起
- Log4cxx日志记录语句挂起