我正在写入一个日志文件,其中包含一个主应用程序可执行文件,我也希望附加其他可执行文件。 我有 CreateFileEx 打开并从所有可执行文件正确写入,但是当子可执行文件写入该文件(并且成功)然后父可执行文件写入文件之后,不幸的是它会覆盖子项写入的内容。 例如。。。
1) Parent opens log.
2) Parent writes 'Line A' to log
Log: 'Line an'
3) Parent launches child executable
4) Child writes 'Child Line A' to log
Log: 'Line AnChild Line An'
5) Parent writes 'Line B' to log.
Log: 'Line AnLine Bn
我一直在使用 LockFileEx/UnlockFileEx(设置为偏移量 0 和长度 MAXDWORD),甚至尝试 SetFilePointer 将该指针移动到末尾都没有成功。 即在上面的序列中写入将等于。
a) LockFileEx
b) SetFilePointer
c) ... write data ...
d) UnlockFileEx
注意:我添加了正确的权限,例如打开文件时没有缓冲等,甚至尝试了FlushFileBuffers但没有成功。
我假设父文件HANDLE以某种方式不知道这些更改,因此SetFilePointer(fHandle,0,NULL,FILE_END)认为它已经在末尾。
有什么想法吗?
提前致谢-提姆
我不确定您的代码出了什么问题,您必须提供其整个实现 - 伪代码描述太少了。我的建议是,不要使用文件锁定,要使用带有普通常规文件附加的互斥锁,您可以使用包装类 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();
}
};