我对某些事感到好奇。我正在开发Windows服务并将所有诊断事件记录到Windows事件日志中。因此,当服务运行时,我打开事件查看器(来自管理工具)以查看我的服务操作的结果。
除了我需要卸载程序的时候(再次,出于测试目的),这很有效。由于一些奇怪的原因,事件查看器保持对我的服务的.exe映像文件的锁定,因此卸载程序无法使用错误代码ERROR_SHARING_VIOLATION
删除它:
The process cannot access the file because it is being used by another process.
这种情况只发生在Vista和更高版本的操作系统上,似乎不是XP的问题。
知道如何让事件查看器释放文件锁吗? (我问的是程序化的方法。我显然可以手动关闭它,但那不是我想要的。)
答案 0 :(得分:5)
Vista中引入的一个鲜为人知的功能叫做Restart Manager,它可以帮助你通过用户模式代码释放文件锁。由于您将其标记为C ++,基于this article,这里有一个小代码示例:
#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;
}
答案 1 :(得分:1)
我以这种方式释放了锁:
答案 2 :(得分:0)
我刚遇到同样的问题。 DLL被svchost.exe进程锁定(Windows音频,DHCP客户端,Windows事件日志,TCP / IP NetBIOS助手,安全中心,任务计划程序)
解决方案:关闭事件查看器! :)