代码之家  ›  专栏  ›  技术社区  ›  Rob

多个DLL正在写入同一文本文件?

  •  1
  • Rob  · 技术社区  · 15 年前

    我想向我的COM对象(DLL)添加日志记录支持,并且通常至少要加载此对象的两个实例。我希望两个DLL都能将行写入同一个文本文件,但担心这会给我带来问题。这有可能实现吗?我认为单一的Windows API是正确的吗 WriteFile 呼叫是原子的?两个进程都可以打开同一个文件进行写入吗?

    我想用STL处理这里的文件( std::ofstream 如果可能的话。我的另一个想法是对每个DLL使用单独的日志,但是单个日志更容易管理。

    1 回复  |  直到 15 年前
        1
  •  2
  •   Alexey Malistov    15 年前
    #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);
    }
    

    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;
    }