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

发布于 2024-08-22 10:10:30 字数 271 浏览 1 评论 0原文

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

如果可能的话,我想在此处使用 STL 进行文件处理 (std::ofstream)。我的另一个想法是为每个 DLL 使用单独的日志,但单个日志会更容易管理。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

饮湿 2024-08-29 10:10:30
#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;
}
#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;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文