Tracing messages with Windows

The OutputDebugString function is used to send messages to a debugger. The function does this through a shared memory section called DBWIN_BUFFER. Shared memory means that any process can access this memory, and so Windows provides two event objects called DBWIN_BUFFER_READY and DBWIN_DATA_READY that control read and write access to this memory. These event objects are shared between processes and can be in a signalled or unsignalled state. A debugger will indicate that it is no longer using the shared memory by signalling the DBWIN_BUFFER_READY event, at which point the OutputDebugString function can write the data to the shared memory. The debugger will wait on the DBWIN_DATA_READY event, which will be signalled by the OutputDebugString function when it has finished writing to the memory and it is safe to read the buffer. The data written to the memory section will be the process ID of the process that called the OutputDebugString function, followed by a string of up to 4 KB of data.

The problem is that when you call the OutputDebugString function it will wait on the DBWIN_BUFFER_READY event, which means that when you use this function you are coupling the performance of your application to the performance of another process, which is usually a debugger (but may not be). It is very easy to write a process to access the DBWIN_BUFFER shared memory section and get access to the associated event objects, so it may be possible that your production code will run on a machine where someone has such an application running. For this reason, it is vitally important that you use conditional compilation so that the OutputDebugString function is only used in debug builds--code that will never be released to your customers:

    extern void run_code(); 

int main()
{
#ifdef _DEBUG
OutputDebugStringA("Application startedn");
#endif

run_code();

#ifdef _DEBUG
OutputDebugStringA("Application endedn");
#endif
return 0;
}

You will need to include the windows.h header file to compile this code. As for the _RPT example, you will have to run this code under a debugger to see the output, or have an application like DebugView (available from Microsoft's Technet website) running.

Windows provides the DBWinMutex mutex object to act as an overall key to accessing this shared memory and event objects. As the name suggests, when you have a handle to a mutex you will have mutually exclusive access to the resource. The problem is that processes do not have to have a handle to this mutex to use these resources and consequently you have no guarantee that, if your application thinks it has exclusive access that it will really have exclusive access.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset