简体   繁体   中英

Redirecting std::cout when program is run as a service

I have a c++ program that prints to the screen using 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?

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.

There's basically infinite options. The first few that come to mind:

Pass around an ostream reference

You could pass around an std::ostream reference:

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

Example from 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("/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.)

Piping

I doubt this is possible with a Windows service, but if it is, there's always the classic redirection:

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());
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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