tags:

views:

38

answers:

1

I want to add logging support to a COM object (DLL) of mine, and there are usually at least two instances of this object loaded. I want both of the DLLs to be able to write lines to the same text file but am worried that this is going to give me problems. Is this possible to achieve? Am I right in thinking that a single Windows API WriteFile call is atomic? Can two processes both open the same file for writing?

I'd like to use the STL for the file handling here (std::ofstream) if possible. My other idea is to use a separate log per-DLL but a single log would be much easier to manage.

+1  A: 
#include <iostream>
#include <fstream>
#include <windosws.h>

struct Mutex {
    Mutex () {
       h = ::CreateMutex(0, false, "{any-GUID-1247965802375274724957}");
    }
    ~Mutex () {
       ::CloseHandle(h);
    }        
    HANDLE h;
};

Mutex mutex; // GLOBAL mutex

void dll_write_func() {
    ::WaitForSingleObject(mutex.h, INFINITE);
    ////////////////
    // Write here
    std::ofstrem f("output.txt");
    f << "Test" << std::endl;
    ////////////////
    ::ReleaseMutex(mutex.h);
}

Or

struct MutexLock {
    explicit MutexLock(Mutex & m) : m(m) {
        ::WaitForSingleObject(m.h, INFINITE);
    }
    ~MutexLock() {
         ::ReleaseMutex(m.h);
    }
    Mutex & m;
};

void dll_write_func2() {
    MutexLock mlock(mutex);

    // Write here
    std::ofstrem f("output.txt");
    f << "Auto mutex Release" << std::endl;
}
Alexey Malistov
Brilliant! Thank you!
Rob