本文介绍了升压:如何创建一个线程,这样就可以控制所有的标准输出,标准错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我C语言创建一个Win32控制台应用程序++。我使用一些API(不是我的,我不能修改其源)。这是写,这样它写入一些信息上的控制台屏幕不问......每次我把它(每秒48次),所以我想放入一些线和限制其输出能力,但我需要得到通知时,该线程将尝试一些输出信息这对我很重要。我有标准的字符串消息文本。如何做这样的事情在C ++使用boost?

I create a win32 console app in C++. I use some API (not mine, and I can not modify its sources). It Is written so that it writes some of its info onto console screen not asking... each time I call it (48 times per second) So I want to put it into some thread and limit its output capabilities, but I need to get notified when that thread will try to output some message which is important for me. I have message text in standard string. How to do such thing in C++ using boost?

推荐答案

这功能不存在升压。你可以,但是,使用来代替标准输出描述:

That feature does not exist in Boost. You can, however, use _dup2 to replace the standard out descriptor:

#include <cstddef>
#include <cstdio>
#include <cstdlib>
#include <io.h>
#include <iostream>
#include <windows.h>

int main()
{
    HANDLE h = CreateFile(TEXT("test.txt"), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
    if (0 == SetStdHandle(STD_OUTPUT_HANDLE, h)) {
        std::fprintf(stderr, "`SetStdHandle` failed with error %d\n", (int)GetLastError());
        return EXIT_FAILURE;
    }

    int h_desc = _open_osfhandle((long)h, 0);
    _dup2(h_desc, STDOUT_FILENO);

    std::printf("test\r\n"); // This actually writes to `h`.
    std::fflush(stdout);

    std::cout << "another test" << std::endl; // Also writes to `h`

    CloseHandle(h);
    return EXIT_SUCCESS;
}

从本质上讲这是什么招确实是让你重定向所有写入标准输出的std :: COUT ,和 GetStdHandle(STD_OUTPUT_HANDLE)到您选择的一个可写的句柄( ^ h )。当然,你可以使用来创建可写的句柄( ^ h ),并在另一个线程读取结尾阅读。

Essentially what this trick does is allow you to redirect all writes to stdout, std::cout, and GetStdHandle(STD_OUTPUT_HANDLE) to a writable handle of your choosing (h). Of course, you can use CreatePipe to create the writable handle (h) and read from the readable end in another thread.

编辑:如果您正在寻找一个跨平台的解决方案,请注意,这一招是POSIX兼容的系统更容易,因为的是在 unistd.h中和可写处理已描述符。

If you are looking for a cross-platform solution, note that this trick is even easier on POSIX-compatible systems because dup2 is a standard function in unistd.h and "writable handles" are already descriptors.

这篇关于升压:如何创建一个线程,这样就可以控制所有的标准输出,标准错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 10:43
查看更多