【问题标题】:Win32 Log file appending with shared process writes附加共享进程写入的 Win32 日志文件
【发布时间】:2016-01-21 02:52:40
【问题描述】:

我正在写入一个带有主应用程序可执行文件的日志文件,我还希望附加其他可执行文件。我已经从所有可执行文件中正确打开并写入了 CreateFileEx,但是当子可执行文件写入该文件(并且它成功)然后父 exe 写入文件之后,不幸的是它会覆盖子文件写入的内容。比如……

1) Parent opens log.
2) Parent writes 'Line A' to log
   Log: 'Line a\n'
3) Parent launches child executable
4) Child writes 'Child Line A' to log
   Log: 'Line A\nChild Line A\n'
5) Parent writes 'Line B' to log.
   Log: 'Line A\nLine B\n

我一直在使用 LockFileEx / UnlockFileEx(设置为偏移量 0 和长度为 MAXDWORD),甚至尝试使用 SetFilePointer 将该指针移动到末尾,但均未成功。 IE。在上面的序列中写入将等同于。

a) LockFileEx
b) SetFilePointer
c) ... write data ...
d) UnlockFileEx

注意:我添加了正确的权限,例如打开文件时不缓冲等,甚至尝试了 FlushFileBuffers 也没有成功。

我会假设父文件 HANDLE 不知何故不知道更改,因此 SetFilePointer(fHandle,0,NULL,FILE_END) 认为它已经结束了。

有什么想法吗?

提前致谢 - 蒂姆

【问题讨论】:

  • 当您尝试自行开发,而不是使用经过良好测试的系统服务时,就会发生这种情况。 Event Tracing for Windows 确实,你正在尝试实现。

标签: file winapi locking


【解决方案1】:

我不确定你的代码有什么问题,你必须提供它的整个实现——伪代码描述太少了。我建议不要使用文件锁定,而是使用带有普通常规文件附加的互斥锁,您可以使用包装类 CMutexEx 和 CMutexExHelper,如下所示,然后日志记录如下所示:

  CMutexEx mtx("myapplogmutex", 250);
  CMutexExHelper mthHelper(mtx);
  if ( mthHelper.Aquire() ) {
    // Log to file, open it and after appending close
  }

我不确定这会有多有效,但至少应该是安全的。

CMutexEx 和 CMutexExHelper 的实现:

class CMutexEx {
public:
  HANDLE hMutex;
  DWORD dwWait;

  explicit CMutexEx(const TCHAR* szName, DWORD dwWait=25) : hMutex(0) { 
    hMutex = CreateMutex(NULL, FALSE, szName); 
    this->dwWait = dwWait;
  }

  bool Aquire() {    
    if ( !hMutex ) return false;

    DWORD dwWaitResult = WaitForSingleObject(hMutex, dwWait);
    if ( dwWaitResult != WAIT_OBJECT_0 )
      return false;
    return true;
  }

  void Release() {
    if ( hMutex )
      ReleaseMutex(hMutex);
  }

  ~CMutexEx() {
    CloseHandle(hMutex);
  }
};

class CMutexExHelper {
  CMutexEx& mtx;
public:
  CMutexExHelper(CMutexEx& p_mtx) : mtx(p_mtx) {
  }
  bool Aquire() {    
    return mtx.Aquire();
  }
  ~CMutexExHelper() {
    mtx.Release();
  }
}; 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-09-27
    • 1970-01-01
    • 2016-04-02
    • 1970-01-01
    • 1970-01-01
    • 2010-09-22
    • 1970-01-01
    相关资源
    最近更新 更多