File 添加共享进程写入的Win32日志文件
我正在写入一个日志文件,其中包含一个主应用程序可执行文件,我希望附加其他可执行文件。我已经从所有可执行文件中正确地打开和写入CreateFileEx,但是当子可执行文件写入该文件(并且成功)时,然后父可执行文件写入该文件,不幸的是,它会覆盖子可执行文件写入的内容。例如File 添加共享进程写入的Win32日志文件,file,winapi,locking,File,Winapi,Locking,我正在写入一个日志文件,其中包含一个主应用程序可执行文件,我希望附加其他可执行文件。我已经从所有可执行文件中正确地打开和写入CreateFileEx,但是当子可执行文件写入该文件(并且成功)时,然后父可执行文件写入该文件,不幸的是,它会覆盖子可执行文件写入的内容。例如 1) Parent opens log. 2) Parent writes 'Line A' to log Log: 'Line a\n' 3) Parent launches child executable 4) Chi
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将指针移动到末尾,但都没有成功。也就是说,在上面的顺序中,写入将等同于
a) LockFileEx
b) SetFilePointer
c) ... write data ...
d) UnlockFileEx
注意:我添加了正确的权限,例如打开文件时没有缓冲等,甚至尝试刷新FileBuffers也没有成功
我假设父文件句柄不知何故不知道这些更改,因此SetFilePointer(fHandle,0,NULL,file_END)认为它已经在末尾了
有什么想法吗
提前谢谢
-Tim我不确定您的代码有什么问题,您必须提供它的整个实现-伪代码描述太少。我建议您不要使用文件锁定,而是使用互斥锁和常规的文件附加,您可以使用包装类CMutexEx和CMutexExHelper,如下所示,然后日志记录如下所示:
CMutexEx mtx("myapplogmutex", 250);
CMutexExHelper mthHelper(mtx);
if ( mthHelper.Aquire() ) {
// Log to file, open it and after appending close
}
我不确定这会有多高效,但至少应该是安全的
CMutexEx和CMUTEXHELPER的实现:
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();
}
};
当您尝试使用自己的系统服务而不是使用经过良好测试的系统服务时,就会发生这种情况。是的,您正试图实现什么。