fprintf() / std::cout 不会将部分字符串打印到 stdout/stderr

fprintf() / std::cout doesn't print part of the string to stdout/stderr

我在使用 stdout/stderr 时遇到了这个奇怪的问题。

我想为无法将原始代码放在这里而道歉,它太长/依赖的库太多等等...
因此,如果您遇到过类似的情况,或者在没有获得原始代码的情况下可能导致此问题的原因,请告诉我,仅提供我尝试做的简单事情的想法和示例:

为了打印,我使用对齐方式,如下所示:

fprintf(stdout, "%*s\n", -printWidth, someEnumToStr[i]);
fprintf(stdout, "%s\n", aString);
fprintf(stdout, "%u\n", num);

aStringstd::string。有时我从 std::ostringstream.
构造 aString 有时我用 snprintf().

构造它

有知道的请告诉我


插图:

deadline_timer..... every 1 sec... my_print()
boost::asio::io_service.run

my_print() {

    for(std::map<>::iterator... begin, end, ++it....) {
        fprintf()s....
    }
}

输出可能卡在缓冲区中,并且在程序终止之前未刷新。

尝试在程序末尾添加 exit(0),看看是否有帮助。

http://www.cplusplus.com/reference/cstdlib/exit/

All C streams (open with functions in <cstdio>) are closed (and flushed, if buffered), and all files created with tmpfile are removed.

不可打印的字符可能会破坏终端。

fprintf(stdout,"%s", astdstring.cstr() );

是怎么打印的std::string

我使用 boost::asio,我有一个回调要从 stdin 读取。此读取是 nonblocking - 发生在 async_read_some().
问题是 stdin 变成了 nonblocking,它也导致 stdout 也变成了 nonblocking,因为它们指向相同的文件描述 (explanation)
它导致 fprintf() 调用失败(返回 -1 和 errno 11)并且并非所有输出都打印在屏幕上。

与boost无关
我成功地隔离了问题,以下代码造成了这个问题:

#include <iostream>
#include <string.h>
#include <stdio.h>
#include <fcntl.h>
#include <errno.h>
#include <stdlib.h>

using namespace std;

int main(int argc, char *argv[]) {

    const int problem = 8000;
    const int myBuffSize = 32000;
    char *myBuff = new char[myBuffSize];
    int myoffset = 0;
    memset(myBuff, '-', myBuffSize);
    int flags;

    bool toogle = true;
    bool running = true;

    // Comment from here
    if ((flags = fcntl(STDIN_FILENO, F_GETFL, 0)) < 0) {

        printf("error fcntl()\n");
        return 0;
    }
    if (fcntl(STDIN_FILENO, F_SETFL, flags | O_NONBLOCK) < 0) {
        printf("error fcntl()\n");
        return 0;
    }
    // Comment until here

    while(running) {

        toogle = toogle ? false : true;
        if (toogle) {

            snprintf(myBuff + problem, myBuffSize - problem, "fin\n\n");
        } else {
            snprintf(myBuff + problem, myBuffSize - problem, "end\n\n");
        }
        fprintf(stdout, "%s", myBuff);
        sleep(1);
    }

    delete[] myBuff;
    return 0;
}

如果您将 // Comment from here 注释为 // Comment untill here,它将打印所有输出(将打印 finend)。

此问题的一个解决方案是使用 fopen(ttyname(STDOUT_FILENO), "w") 打开另一个 fd 到当前 tty 并打印到其中。
我相信另一种解决方案是 async_write() 进入屏幕。