【发布时间】:2014-07-30 16:19:33
【问题描述】:
我有以下代码
void _log_message(const char* fmt, ...)
{
va_list arg;
ofstream logfile;
cout << "Open Log File" << endl;
logfile.open(LOG_FILE, ios::out | ios::app);
if(!logfile.is_open()) return;
time_t t = time(NULL);
struct tm *tmptr = gmtime(&t);
char tmStr[70];
if (tmptr == NULL || strftime(tmStr, sizeof tmStr, "%Y-%m-%d %H:%M:%S", tmptr) == 0)
{
boost::format errFormat("gmtime() failed in file %s at line # %d\n");
logfile << errFormat % __FILE__ % (int)(__LINE__-3) << endl;
}
char* fmtMessage;
va_start(arg, fmt);
vsprintf(fmtMessage, fmt, arg);
va_end(arg);
try
{
cout << "write to logfile\t" << tmStr << "\t" << fmtMessage << endl;
logfile << tmStr << "\t" << fmtMessage << endl;
cout << "close logfile" << endl;
logfile.close();
cout << "close done" << endl;
}
catch(exception e)
{
cout << "Exception: " << e.what() << endl;
}
cout << "exit" << endl;
}
它运行良好,直到输出到日志文件。然后它就停止了。我没有发现任何错误,也没有发现异常。
Open Log File
write to logfile 2014-07-30 16:12:34 Starting...
我用 ps 检查,进程已经死了,没有挂起。
如果我从行尾删除 endl 则它可以工作,但随后在 close 方法调用中再次遇到同样的问题:
Open Log File
write to logfile 2014-07-30 16:15:53 Starting...
close logfile
如果我对 close 方法调用发表评论,那么我会得到最后的“退出”行,但函数永远不会返回。
这是在 main 的第一行调用的函数的第一行调用的,所以我相当确定到那时我不会把任何事情搞得太严重。 我确实通过 valgrind 运行它,但什么也没找到。
并不是所有的 cout 调用都只是调试,而不是程序本身的一部分。
【问题讨论】:
-
您是否尝试将其简化为表现出该行为的最短示例?
-
通过 const 引用捕获异常。而且由于这是 C++,可变参数模板比 C 风格的可变参数函数更受欢迎。