简体   繁体   English

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

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

I have a c++ program that prints to the screen using std::cout. 我有一个c ++程序,使用std :: cout打印到屏幕上。

Sometimes I need to run it as a service. 有时我需要将其作为服务运行。 Is there any way of seeing the cout outputs when it's running as a Windows service? 当它作为Windows服务运行时,有没有办法看到cout输出?

Redirecting the output to a file or some sort of debugging program would be ideal. 将输出重定向到文件或某种调试程序将是理想的选择。

Obviously I could replace the cout with a function that writes to a file, and that's probably what I'll do, but I'm curious to know if there are other solutions. 显然我可以用写入文件的函数替换cout,这可能就是我要做的,但我很想知道是否有其他解决方案。

There's basically infinite options. 基本上有无限的选择。 The first few that come to mind: 首先想到的几个:

Pass around an ostream reference 绕过ostream参考

You could pass around an std::ostream reference: 你可以传递一个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;
}

Replace cout underlying buffer with a file 用文件替换cout底层缓冲区

Example from cplusplus.com : 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";

There's a 1-liner with freopen, but I have a creeping feeling (and this seems to reenforce it in the comments) that it's undefined behavior since stdin and cout can be un-synchronized. 有一个带有freopen的1-liner,但我有一种渐渐的感觉( 似乎在评论中重新强制它)它是未定义的行为,因为stdin和cout可以是不同步的。

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

A logging library 日志库

Not sure of a good one of the top of my head, but you could go full out and use some type of logging library. 不确定我的头脑中的好东西,但你可以全力以赴并使用某种类型的记录库。 (There's also Windows events, though depending on what you're outputting, that might not make sense.) (也有Windows事件,但取决于你输出的内容,这可能没有意义。)

Piping 管道

I doubt this is possible with a Windows service, but if it is, there's always the classic redirection: 我怀疑这可以通过Windows服务实现,但如果是这样的话,总会有经典的重定向:

blah.exe > C:\path\file

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

You could do something like this: 你可以这样做:

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