C ++在运行时保存服务输出

时间:2015-10-23 08:59:42

标签: c++ windows cmd

我想将service.exe的输出收集到我的c ++程序(windows环境)。在简单的情况下,在cmd中调用类似" service.exe> log.txt的"但在我的情况下,服务总是被其他系统调用关闭" taskkill service.exe"导致log.txt中缺少输出。 我怎么解决这个问题?我尝试使用windows _popen,但与简单的系统函数调用相同 - 文件中缺少输出。

代码例如:

void test_of_runtime()
{
std::string result;

/* Create path to service */
boost::filesystem::path work_path(boost::filesystem::current_path());

/* Run servie and save output in log file */
work_path += "\\service.exe > runtime_log.txt";

/* Create another thread which terminate service after 10 seconds */
boost::thread terminate_thread(terminate_thread_func);
terminate_thread.detach();

system(work_path.string().c_str());
}



void terminate_thread_func()
{
std::string terminate_command = "taskkill /F /T /IM service.exe";

/* Wait 10 sec */
boost::this_thread::sleep_for(boost::chrono::seconds(10));

/* Terminate service after 10 sec */
system(terminate_command.c_str());
}

1 个答案:

答案 0 :(得分:0)

除特殊条件外,您应避免使用taskkill /f终止任何任务。正确的方法是将信号发送到正在运行的任务,它应该停止以允许它最终进行一些清理并刷新其缓冲区。

如果service.exe有消息循环,则可以使用PostThreadMessage,前提是您可以使用消息队列访问线程的ID。您通常在CreateProcess调用填充的PROCESS_INFORMATION结构中获取它。

如果service.exe没有消息循环(即它被写为控制台应用程序),它可以使用HandlerRoutine注册SetConsoleCtrlHandler。然后,您可以使用GenerateConsoleCtrlEvent函数发送CTRL_BREAK_EVENT,或使用taskkill 发送/F (仍然不确定最后一个)。您将找到here 中断处理程序的使用示例。

如果以上都不是一个选项,他们service.exe必须随时被强制杀死。这意味着它不应该缓冲它的输出,特别是你不应该用service.exe > log.txt启动它并让它写入stdout,而是给它一个日志文件的名称,理想情况下程序应该使用open write来记录关闭模式。

相关问题