繁体   English   中英

当程序作为服务运行时重定向std :: cout

[英]Redirecting std::cout when program is run as a service

我有一个c ++程序,使用std :: cout打印到屏幕上。

有时我需要将其作为服务运行。 当它作为Windows服务运行时,有没有办法看到cout输出?

将输出重定向到文件或某种调试程序将是理想的选择。

显然我可以用写入文件的函数替换cout,这可能就是我要做的,但我很想知道是否有其他解决方案。

基本上有无限的选择。 首先想到的几个:

绕过ostream参考

你可以传递一个std :: ostream引用:

void someFunc(std::ostream& out) {
    //someFunc doesn't need to know whether out is a file, cout, or whatever
    out << "hello world" << std::endl;
}

用文件替换cout底层缓冲区

cplusplus.com的示例:

streambuf *psbuf, *backup;
ofstream filestr;
filestr.open ("test.txt");

backup = cout.rdbuf();     // back up cout's streambuf

psbuf = filestr.rdbuf();   // get file's streambuf
cout.rdbuf(psbuf);         // assign streambuf to cout

cout << "This is written to the file";

有一个带有freopen的1-liner,但我有一种渐渐的感觉( 似乎在评论中重新强制它)它是未定义的行为,因为stdin和cout可以是不同步的。

freopen("/path/to/file", "r", stdout);
//cout is now writing to path/to/file

日志库

不确定我的头脑中的好东西,但你可以全力以赴并使用某种类型的记录库。 (也有Windows事件,但取决于你输出的内容,这可能没有意义。)

管道

我怀疑这可以通过Windows服务实现,但如果是这样的话,总会有经典的重定向:

blah.exe > C:\path\file

简单的解决方案是SetStdHandle(STD_OUTPUT_HANDLE, your_new_handle)

你可以这样做:

class MyTerminal {
    std::stringstream terminalText;
}

class MyWindow {
public:
     void OnUpdate();
protected:
CTextbox m_textbox;
MyTerminal m_terminal;
}

void MyWindow::OnUpdate()
{
    m_textBox.setText(m_terminal.terminalText.str());
    m_terminal.terminalText.str(std::string());
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM