Windows事件查看器锁定了我的EXE文件

c00*_*0fd 6 c++ windows winapi event-viewer

我很好奇.我正在开发Windows服务并将所有诊断事件记录到Windows事件日志中.因此,当服务运行时,我打开事件查看器(来自管理工具)以查看我的服务操作的结果.

除了我需要卸载程序的时候(这也是出于测试目的),这非常有用.出于某种奇怪的原因,事件查看器会锁定我的服务的.exe映像文件,因此卸载程序无法删除它错误代码ERROR_SHARING_VIOLATION:

The process cannot access the file because it is being used by another process.
Run Code Online (Sandbox Code Playgroud)

这只发生在Vista和更高版本的操作系统上,似乎不是XP的问题.

知道如何让事件查看器释放文件锁吗?(我问的是程序化的方法.我显然可以手动关闭它,但那不是我想要的.)

Sam*_*Sam 8

我这样释放锁:

  1. 开始 -> 服务
  2. 查找Windows 事件日志
  3. 右键->重新启动


ahm*_*md0 5

Vista中引入了一个名为Restart Manager的鲜为人知的功能,它可以帮助您通过用户模式代码释放文件锁.由于您将其标记为C++,基于本文,这里有一个小代码示例:

#include <RestartManager.h>
#pragma comment(lib ,"Rstrtmgr.lib")

BOOL ReleaseFileLock(LPCTSTR pFilePath)
{
    BOOL bResult = FALSE;

    DWORD dwSession;
    WCHAR szSessionKey[CCH_RM_SESSION_KEY+1] = { 0 };
    DWORD dwError = RmStartSession(&dwSession, 0, szSessionKey);
    if (dwError == ERROR_SUCCESS) 
    {
        dwError = RmRegisterResources(dwSession, 1, &pFilePath,
            0, NULL, 0, NULL);
        if (dwError == ERROR_SUCCESS) 
        {
            UINT nProcInfoNeeded = 0;
            UINT nProcInfo = 0;
            RM_PROCESS_INFO rgpi[1];
            DWORD dwReason;

            dwError = RmGetList(dwSession, &nProcInfoNeeded,
                &nProcInfo, rgpi, &dwReason);
            if (dwError == ERROR_SUCCESS ||
                dwError == ERROR_MORE_DATA) 
            {
                if(nProcInfoNeeded > 0)
                {
                    //If current process does not have enough privileges to close one of
                    //the "offending" processes, you'll get ERROR_FAIL_NOACTION_REBOOT
                    dwError = RmShutdown(dwSession, RmForceShutdown, NULL);
                    if (dwError == ERROR_SUCCESS)
                    {
                        bResult = TRUE;
                    }
                }
                else
                    bResult = TRUE;
            }
        }
    }

    RmEndSession(dwSession);

    SetLastError(dwError);
    return bResult;
}
Run Code Online (Sandbox Code Playgroud)