CSDN博客

img zyyuce

捕捉 OutputDebugString 输出的字符串

发表于2004/10/26 18:59:00  660人阅读

        在调试状态下,VC 等调试器可以捕捉程序中的 OutputDebugString 输出的信息。其实 OutputDebugString 就是往一片共享影射的内存中写入了一段数据,并创建了两个 Enevt,指明数据写入事件被触发。在非调试状态下,我们也可以通过编程实现捕捉 OutputDebugString 的输出。下面的代码演示了如何获取这些信息:
DWORD WINAPI CDebugTrack::TrackProc(PVOID pvParam)
{
HANDLE hMapping = NULL;
HANDLE hAckEvent = NULL;
PDEBUGBUFFER pdbBuffer = NULL;
TCHAR tzBuffer[MAX_DebugBuffer];

_Try
{
// 设置初始结果
m_dwResult = ERROR_INVALID_HANDLE;

// 打开事件句柄
hAckEvent = CreateEvent(NULL, FALSE, FALSE, TEXT("DBWIN_BUFFER_READY"));
_LeaveIf(hAckEvent == NULL);

m_hReadyEvent = CreateEvent(NULL, FALSE, FALSE, TEXT("DBWIN_DATA_READY"));
_LeaveIf(m_hReadyEvent == NULL);

// 创建文件映射
hMapping = CreateFileMapping(INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE, 0, MAX_DebugBuffer, TEXT("DBWIN_BUFFER"));
_LeaveIf(hMapping == NULL);

// 映射调试缓冲区
pdbBuffer = (PDEBUGBUFFER) MapViewOfFile(hMapping, FILE_MAP_READ, 0, 0, 0);
_LeaveIf(pdbBuffer == NULL);

// 循环
for (m_dwResult = ERROR_SIGNAL_PENDING; (m_dwResult == ERROR_SIGNAL_PENDING); )
{
// 等待缓冲区数据
SetEvent(hAckEvent);
if (WaitForSingleObject(m_hReadyEvent, INFINITE) == WAIT_OBJECT_0)
{
// 如果是继续等待,否则表示主线程发出了停止信号,退出当前线程
if (m_dwResult == ERROR_SIGNAL_PENDING)
{
// 添加新项
_AStrToStr(tzBuffer, pdbBuffer->szString);
CListView::AddDebugItem(tzBuffer, pdbBuffer->dwProcessId);
}
}
else
{
// 等待失败
m_dwResult = WAIT_ABANDONED;
}
}
}
_Finally
{
// 释放
if (pdbBuffer)
{
UnmapViewOfFile(pdbBuffer);
}

_SafeCloseHandle(hMapping);
_SafeCloseHandle(m_hReadyEvent);
_SafeCloseHandle(hAckEvent);

PostMessage(CMainWnd::m_hWnd, WM_COMMAND, IDC_DebugTrack, m_dwResult);

// 返回结果
return m_dwResult;
}
}

当然,你也可以选择 SysinternalsDebugView,功能更强大(可以远程监视、可以监视内核输出),不过没有 DebugTrack 用起来方便。

有关 OutputDebugString 的深入分析,可以参看这篇文章: 请查看文章 (E文): http://www.unixwiz.net/techtips/outputdebugstring.html

阅读全文
0 0

相关文章推荐

img
取 消
img