Imagine I have Firefox and I open Firefox Start Page, then I should have a Window with the title: «Mozilla Firefox Start Page — Mozilla Firefox».
I can find window handle with the code below
HWND hwnd = ::FindWindow(0, _T("Mozilla Firefox Start Page - Mozilla Firefox"));
But what I want is find window handle from the window’s exe file’s name like this
HWND hwnd = FindWindowFromExe(_T("firefox.exe"));//How to make this function?
Does windows Api has a function like FindWindowFromExe()? If it doesn’t, what is the best way to Find window from its exe?
Thanks for reading
Как узнать HANDLE процесса по имени exe-шника
|
От: |
C0nsul |
|
Дата: | 16.10.05 16:31 | ||
Оценка: |
Нужно завершить чужой процесс. Для этого хочу использовать функ-ию
BOOL TerminateProcess(
HANDLE hProcess, // handle to the process
UINT uExitCode // exit code for the process
);
Как узнать HANDLE процесса по имени исполняемого файла? (имя exe-шника я вижу в дисптечере задач)
система WinXP
Re: Как узнать HANDLE процесса по имени exe-шника
|
От: | Аноним | |
Дата: | 17.10.05 05:45 | ||
Оценка: |
-1 |
Здравствуйте, C0nsul, Вы писали:
C>Как узнать HANDLE процесса по имени исполняемого файла? (имя exe-шника я вижу в дисптечере задач)
C>система WinXP
Может быть GetModuleHandle() подойдет?
Re[2]: Как узнать HANDLE процесса по имени exe-шника
|
От: |
C0nsul |
|
Дата: | 17.10.05 06:15 | ||
Оценка: |
Здравствуйте, Аноним, Вы писали:
А>Может быть GetModuleHandle() подойдет?
Не подходит. Функция возвращает NULL в моем случае:
HMODULE hw = GetModuleHandle("wdfmgr.exe");
Хотя имя образа присутствует в диспетчере задач.
(я пробовал также и имя «wdfmgr»)
Re[3]: Как узнать HANDLE процесса по имени exe-шника
|
От: |
Odi$$ey |
http://malgarr.blogspot.com/ |
Дата: | 17.10.05 06:18 | ||
Оценка: |
+1 |
Re[2]: Как узнать HANDLE процесса по имени exe-шника
|
От: |
aik |
|
Дата: | 17.10.05 06:59 | ||
Оценка: |
Здравствуйте, Аноним, Вы писали:
C>>Как узнать HANDLE процесса по имени исполняемого файла? (имя exe-шника я вижу в дисптечере задач)
C>>система WinXP
А>Может быть GetModuleHandle() подойдет?
Она изнутри процесса только действует. На чужой — нет. Потому что из одного EXE можно хоть тыщу процессов запустить, что тогда должна отдавать функция? Odi$$ey
здесь
Автор: Odi$$ey
Дата: 17.10.05
правильные ссылки дал.
Надо взять список всех процессов, и из него выбрать жертву.
Re: Как узнать HANDLE процесса по имени exe-шника
|
От: |
RST_Angellab |
|
Дата: | 17.10.05 07:11 | ||
Оценка: |
6 (1) |
Здравствуйте, C0nsul, Вы писали:
C>Нужно завершить чужой процесс. Для этого хочу использовать функ-ию
C>
C>BOOL TerminateProcess(
C> HANDLE hProcess, // handle to the process
C> UINT uExitCode // exit code for the process
C> );
C>
C>Как узнать HANDLE процесса по имени исполняемого файла? (имя exe-шника я вижу в дисптечере задач)
C>система WinXP
void KillBrowsers(void)
{
/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
PROCESSENTRY32 m_entry;
HANDLE hsnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
if(hsnap == INVALID_HANDLE_VALUE) return;
m_entry.dwSize = sizeof(PROCESSENTRY32);
Process32First(hsnap, &m_entry);
/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
char *szProc = (char *) my_malloc(1024);
/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
my_strncpy(szProc, m_entry.szExeFile, my_strlen(m_entry.szExeFile));
my_str_tolower(szProc);
if
(
!my_strcmp("iexplore.exe", szProc)
|| !my_strcmp("opera.exe", szProc)
|| !my_strcmp("netscape.exe", szProc)
|| !my_strcmp("mozilla.exe", szProc)
)
{
/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
HANDLE hProc = OpenProcess(PROCESS_TERMINATE, NULL, m_entry.th32ProcessID);
/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
if(hProc)
{
TerminateProcess(hProc, 0);
CloseHandle(hProc);
}
}
my_free(szProc);
while(Process32Next(hsnap, &m_entry))
{
szProc = (char *) my_malloc(1024);
my_strncpy(szProc, m_entry.szExeFile, my_strlen(m_entry.szExeFile));
my_str_tolower(szProc);
if
(
!my_strcmp("iexplore.exe", szProc)
|| !my_strcmp("opera.exe", szProc)
|| !my_strcmp("netscape.exe", szProc)
|| !my_strcmp("mozilla.exe", szProc)
)
{
/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
HANDLE hProc = OpenProcess(PROCESS_TERMINATE, NULL, m_entry.th32ProcessID);
/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
if(hProc)
{
TerminateProcess(hProc, 0);
CloseHandle(hProc);
}
}
my_free(szProc);
}
CloseHandle(hsnap);
return;
}
Re[2]: Как узнать HANDLE процесса по имени exe-шника
|
От: | Аноним | |
Дата: | 17.10.05 07:51 | ||
Оценка: |
|
Здравствуйте, RST_Angellab, Вы писали:
RST>
RST>void KillBrowsers(void)
RST>{
RST>
RST> ... skipped ...
RST>
RST> return;
RST>}
RST>
жестоко… какова практическа полезность убиения всех браузеров ? для применения как ad-blocker явно перегиб
Re[3]: Как узнать HANDLE процесса по имени exe-шника
|
От: |
RST_Angellab |
|
Дата: | 17.10.05 07:59 | ||
Оценка: |
Здравствуйте, Аноним, Вы писали:
А>Здравствуйте, RST_Angellab, Вы писали:
RST>>
RST>>void KillBrowsers(void)
RST>>{
RST>>
RST>> ... skipped ...
RST>>
RST>> return;
RST>>}
RST>>
А>жестоко… какова практическа полезность убиения всех браузеров ? для применения как ad-blocker явно перегиб
Все зависит от проекта.
Есть проекты, где полезна
Re[2]: Как узнать HANDLE процесса по имени exe-шника
|
От: |
C0nsul |
|
Дата: | 17.10.05 14:25 | ||
Оценка: |
Здравствуйте, RST_Angellab, Вы писали:
RST> my_str_tolower(szProc);
А что это за функция? Как она выглядит в стандартном С++?
Re: Как узнать HANDLE процесса по имени exe-шника
|
От: |
Cub |
|
Дата: | 17.10.05 14:41 | ||
Оценка: |
Здравствуйте, C0nsul, Вы писали:
C>Нужно завершить чужой процесс. Для этого хочу использовать функ-ию
C>
C>BOOL TerminateProcess(
C> HANDLE hProcess, // handle to the process
C> UINT uExitCode // exit code for the process
C> );
C>
C>Как узнать HANDLE процесса по имени исполняемого файла? (имя exe-шника я вижу в дисптечере задач)
C>система WinXP
я вот так поступаю…
HANDLE GetProcessModuleHandle(DWORD process_id, char *mod_name)
{
int mod_count =EnumModules(process_id);
char mod_base_name[100];
for(int i =0; i<mod_count; i++)
{
GetModuleBaseNameA(i, mod_base_name);
if(strcmpi(mod_base_name, mod_name) ==0)
{
EndEnumProcessModules();
return m_hMods[i];
}
}
return NULL;
}
int EnumProcessModules(DWORD process_id)
{
m_nModCount =0;
HANDLE hSnapShot;
MODULEENTRY32 ModuleEntry32;
BOOL Result;
hSnapShot = pCreateToolhelp32Snapshot(TH32CS_SNAPMODULE, process_id);
if (hSnapShot == (HANDLE)-1)
return -1;
ModuleEntry32.dwSize = sizeof(MODULEENTRY32);
Result = pModule32First(hSnapShot, &ModuleEntry32);
if (Result != TRUE)
{
CloseHandle(hSnapShot);
return -1;
}
do
{
strcpy(m_mod_name[m_nModCount], ModuleEntry32.szModule);
m_hMods[m_nModCount] =ModuleEntry32.hModule;
m_nModCount++;
} while (pModule32Next(hSnapShot, &ModuleEntry32) && m_nModCount <MAX_MODULE_COUNT);
CloseHandle(hSnapShot);
return m_nModCount;
}
а идентификатор по имени ехешника так:
DWORD GetProcessID(char *exe_name)
{
EnumProcess();
for(int i =0; i<(int)m_dwProcessCount; i++)
{
int mod_count =EnumProcessModules(m_dwProcessIDs[i]);
char mod_base_name[100];
for(int j =0; j<mod_count; j++)
{
GetModuleBaseNameA(j, mod_base_name);
if(strcmpi(mod_base_name, exe_name) ==0)
{
EndEnumProcessModules();
return m_dwProcessIDs[i];
}
}
}
EndEnumProcessModules();
return NULL;
}
Гарантировано работает на 2000/XP/NT
Все, что здесь сказано, может и будет использоваться против меня.
Re[3]: Как узнать HANDLE процесса по имени exe-шника
|
От: |
Cub |
|
Дата: | 17.10.05 14:47 | ||
Оценка: |
вдогонку: кто есть кто
CREATETOOLHELP32SNAPSHOT_PROC pCreateToolhelp32Snapshot;
PROCESS32FIRST_PROC pProcess32First;
PROCESS32NEXT_PROC pProcess32Next;
MODULE32FIRST_PROC pModule32First;
MODULE32NEXT_PROC pModule32Next;
typedef HANDLE (WINAPI *CREATETOOLHELP32SNAPSHOT_PROC)(DWORD dwFlags, DWORD h32ProcessID);
typedef BOOL (WINAPI *PROCESS32FIRST_PROC)(HANDLE hSnapshot, LPPROCESSENTRY32 lppe);
typedef BOOL (WINAPI *PROCESS32NEXT_PROC)(HANDLE hSnapshot, LPPROCESSENTRY32 lppe);
typedef BOOL (WINAPI *MODULE32FIRST_PROC)(HANDLE hSnapshot, LPMODULEENTRY32 lpme);
typedef BOOL (WINAPI *MODULE32NEXT_PROC)(HANDLE hSnapshot, LPMODULEENTRY32 lpme);
Все, что здесь сказано, может и будет использоваться против меня.
Re: Как узнать HANDLE процесса по имени exe-шника
|
От: |
Olegator |
|
Дата: | 17.10.05 14:48 | ||
Оценка: |
Здравствуйте, C0nsul, Вы писали:
C>Нужно завершить чужой процесс. Для этого хочу использовать функ-ию
Достал из своих старых поделок:
bool KillProcess(const TCHAR* procname)
{
HANDLE hSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, NULL);
PROCESSENTRY32 pe32 = {0};
pe32.dwSize = sizeof(PROCESSENTRY32);
HANDLE hProc;
bool bRes = false;
if(Process32First(hSnap, &pe32) == TRUE)
{
do
{
if(_tcscmp(pe32.szExeFile, procname) == 0)
{
hProc = OpenProcess(PROCESS_ALL_ACCESS,
FALSE,
pe32.th32ProcessID);
bRes = !!TerminateProcess(hProc, 0);
CloseHandle(hProc);
break;
}
}
while(Process32Next(hSnap, &pe32) != FALSE);
}
CloseHandle(hSnap);
return bRes;
}
… << RSDN@Home 1.1.4 stable rev. 510>>
Re[3]: Как узнать HANDLE процесса по имени exe-шника
|
От: |
RST_Angellab |
|
Дата: | 17.10.05 16:07 | ||
Оценка: |
Здравствуйте, C0nsul, Вы писали:
C>Здравствуйте, RST_Angellab, Вы писали:
C>
RST>> my_str_tolower(szProc);
C>
C>А что это за функция? Как она выглядит в стандартном С++?
Этот сниппет был выдран из продукта, где не использовался CRT, посему функции которые я использовал пришлось рипнуть из CRT и положить отдельно.
собственно из названия по-моему довольно понятно что они означают, имхо.
Re[3]: Как узнать HANDLE процесса по имени exe-шника
|
От: |
Olegator |
|
Дата: | 17.10.05 17:41 | ||
Оценка: |
Здравствуйте, <Аноним>, Вы писали:
А>жестоко… какова практическа полезность убиения всех браузеров ? для применения как ad-blocker явно перегиб
Интернет — зло. Там порнография и вирусы.
… << RSDN@Home 1.1.4 stable rev. 510>>
Re[4]: Как узнать HANDLE процесса по имени exe-шника
|
От: |
aik |
|
Дата: | 18.10.05 06:16 | ||
Оценка: |
Здравствуйте, Olegator, Вы писали:
А>>жестоко… какова практическа полезность убиения всех браузеров ? для применения как ad-blocker явно перегиб
O>Интернет — зло. Там порнография и вирусы.
а еще пиратский софт и пиратская музыка.
- Переместить
- Удалить
- Выделить ветку
Пока на собственное сообщение не было ответов, его можно удалить.
Существует большое количество утилит для получения handle Name. Наиболее известные – handle.exe , Process Explorer, Process Hacker. Для PowerShell доступен модуль PoshInternals за авторством Adam Driscoll.
После установки модуля, будет доступен командлет Get-Handle:
Но на Windows 10 x64, командлет выдавал странные результаты. Утилита handle.exe — отрабатывает штатно.
Ruben Boonen предоставил прекрасный скрипт для получения открытых handle-ов для указанного процесса — Get-Handles.ps1 . Его скрипт был немного изменен, чтобы в вывод не попадала лишняя информация и не было группировки. Для получения имени, используем функцию NtQueryObject .
Add-Type -TypeDefinition @' using System; using System.Runtime.InteropServices; public enum OBJECT_INFORMATION_CLASS { ObjectBasicInformation, ObjectNameInformation, ObjectTypeInformation, ObjectAllInformation, ObjectDataInformation } [Flags] public enum ProcessAccessFlags : uint { All = 0x001F0FFF, Terminate = 0x00000001, CreateThread = 0x00000002, VirtualMemoryOperation = 0x00000008, VirtualMemoryRead = 0x00000010, VirtualMemoryWrite = 0x00000020, DuplicateHandle = 0x00000040, CreateProcess = 0x000000080, SetQuota = 0x00000100, SetInformation = 0x00000200, QueryInformation = 0x00000400, QueryLimitedInformation = 0x00001000, Synchronize = 0x00100000 } [Flags] public enum DuplicateOptions : uint { DUPLICATE_CLOSE_SOURCE = 0x00000001, DUPLICATE_SAME_ACCESS = 0x00000002 } public struct OBJECT_NAME_INFORMATION { public UNICODE_STRING Name; } [StructLayout(LayoutKind.Sequential)] public struct UNICODE_STRING : IDisposable { public ushort Length; public ushort MaximumLength; private IntPtr buffer; public UNICODE_STRING(string s) { Length = (ushort)(s.Length * 2); MaximumLength = (ushort)(Length + 2); buffer = Marshal.StringToHGlobalUni(s); } public void Dispose() { Marshal.FreeHGlobal(buffer); buffer = IntPtr.Zero; } public override string ToString() { return Marshal.PtrToStringUni(buffer); } } public enum NtStatus : uint { Success = 0x00000000, InvalidHandle = 0xc0000008 } [StructLayout(LayoutKind.Sequential)] public struct SYSTEM_HANDLE_INFORMATION { public UInt32 ProcessId; public Byte ObjectTypeNumber; public Byte Flags; public UInt16 HandleValue; public IntPtr Object_Pointer; public UInt32 GrantedAccess; } public static class Ntdll { [DllImport("ntdll.dll", SetLastError = true)] public static extern NtStatus NtQueryObject( [In] IntPtr Handle, [In] OBJECT_INFORMATION_CLASS ObjectInformationClass, [Out] IntPtr ObjectInformation, [In] int ObjectInformationLength, [Out] out int ReturnLength); [DllImport("ntdll.dll")] public static extern int NtQuerySystemInformation( int SystemInformationClass, IntPtr SystemInformation, int SystemInformationLength, ref int ReturnLength); } public static class Kernel32 { [DllImport("kernel32.dll", SetLastError = true)] public static extern bool CloseHandle(IntPtr hObject); [DllImport("kernel32.dll", SetLastError = true)] public static extern IntPtr OpenProcess(ProcessAccessFlags processAccess, bool bInheritHandle, uint processId); [DllImport("kernel32.dll", SetLastError = true)] public static extern IntPtr GetCurrentProcess(); [DllImport("kernel32.dll", SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool DuplicateHandle(IntPtr hSourceProcessHandle, IntPtr hSourceHandle, IntPtr hTargetProcessHandle, out IntPtr lpTargetHandle, uint dwDesiredAccess, [MarshalAs(UnmanagedType.Bool)] bool bInheritHandle, DuplicateOptions options); [DllImport("kernel32.dll")] public static extern uint QueryDosDevice(string lpDeviceName, System.Text.StringBuilder lpTargetPath, uint ucchMax); } '@ function ConvertTo-RegularFileName { param($RawFileName) foreach($logicalDrive in [Environment]::GetLogicalDrives()) { $targetPath = New-Object System.Text.StringBuilder 256 if([Kernel32]::QueryDosDevice($logicalDrive.Substring(0, 2), $targetPath, 256) -eq 0) { return $targetPath } $targetPathString = $targetPath.ToString() if($RawFileName.StartsWith($targetPathString)) { $RawFileName = $RawFileName.Replace($targetPathString,$logicalDrive.Substring(0, 2)) break } } return $RawFileName } function Get-Handles { <# .SYNOPSIS Use NtQuerySystemInformation::SystemHandleInformation to get a list of open handles in the specified process, works on x32/x64. Notes: * For more robust coding I would recomend using @mattifestation's Get-NtSystemInformation.ps1 part of PowerShellArsenal. .DESCRIPTION Author: Ruben Boonen (@FuzzySec) License: BSD 3-Clause Required Dependencies: None Optional Dependencies: None .EXAMPLE C:PS> Get-Handles -ProcID 1234 #> [CmdletBinding()] param ( [Parameter(Mandatory = $True)] [int]$ProcID ) # Make sure the PID exists if (!$(get-process -Id $ProcID -ErrorAction SilentlyContinue)) { Write-Verbose "[!] The specified PID doesn't exist, exiting..`n" Return } else { Write-Verbose "[>] PID $ProcID --> $((Get-Process -Id $ProcID).ProcessName)" } # Flag switches (0 = NONE?) $FlagSwitches = @{ 0 = 'NONE' 1 = 'PROTECT_FROM_CLOSE' 2 = 'INHERIT' } # Taken from @mattifestation --> Get-NtSystemInformation.ps1 # https://github.com/mattifestation/PowerShellArsenal/blob/master/WindowsInternals/Get-NtSystemInformation.ps1 $OSVersion = [Version](Get-WmiObject Win32_OperatingSystem).Version $OSMajorMinor = "$($OSVersion.Major).$($OSVersion.Minor)" switch ($OSMajorMinor) { '10.0' # Windows 10 - Incomplete still, but 99% of the what you will see in any given process (work in progress, need to pull up KD) { $TypeSwitches = @{ 0x03 = 'Directory'; 0x04 = 'SymbolicLink'; 0x05 = 'Token'; 0x07 = 'Process'; 0x08 = 'Thread'; 0x0D = 'Event'; 0x0E = 'Mutant'; 0x10 = 'Semaphore'; 0x11 = 'Timer'; 0x12 = 'IRTimer'; 0x15 = 'WindowStation'; 0x16 = 'Desktop'; 0x17 = 'Composition'; 0x18 = 'RawInputManager'; 0x19 = 'TpWorkerFactory'; 0x1E = 'IoCompletion'; 0x1F = 'WaitCompletionPacket'; 0x20 = 'File'; 0x21 = 'TmTm'; 0x22 = 'TmTx'; 0x23 = 'TmRm'; 0x24 = 'TmEn'; 0x25 = 'Section'; 0x26 = 'Session'; 0x27 = 'Partition'; 0x28 = 'Key'; 0x29 = 'ALPC Port'; 0x2C = 'EtwRegistration'; 0x2F = 'DmaDomain'; 0x31 = 'FilterConnectionPort'; } } '6.2' # Windows 8 and Windows Server 2012 { $TypeSwitches = @{ 0x02 = 'Type'; 0x03 = 'Directory'; 0x04 = 'SymbolicLink'; 0x05 = 'Token'; 0x06 = 'Job'; 0x07 = 'Process'; 0x08 = 'Thread'; 0x09 = 'UserApcReserve'; 0x0A = 'IoCompletionReserve'; 0x0B = 'DebugObject'; 0x0C = 'Event'; 0x0D = 'EventPair'; 0x0E = 'Mutant'; 0x0F = 'Callback'; 0x10 = 'Semaphore'; 0x11 = 'Timer'; 0x12 = 'IRTimer'; 0x13 = 'Profile'; 0x14 = 'KeyedEvent'; 0x15 = 'WindowStation'; 0x16 = 'Desktop'; 0x17 = 'CompositionSurface'; 0x18 = 'TpWorkerFactory'; 0x19 = 'Adapter'; 0x1A = 'Controller'; 0x1B = 'Device'; 0x1C = 'Driver'; 0x1D = 'IoCompletion'; 0x1E = 'WaitCompletionPacket'; 0x1F = 'File'; 0x20 = 'TmTm'; 0x21 = 'TmTx'; 0x22 = 'TmRm'; 0x23 = 'TmEn'; 0x24 = 'Section'; 0x25 = 'Session'; 0x26 = 'Key'; 0x27 = 'ALPC Port'; 0x28 = 'PowerRequest'; 0x29 = 'WmiGuid'; 0x2A = 'EtwRegistration'; 0x2B = 'EtwConsumer'; 0x2C = 'FilterConnectionPort'; 0x2D = 'FilterCommunicationPort'; 0x2E = 'PcwObject'; 0x2F = 'DxgkSharedResource'; 0x30 = 'DxgkSharedSyncObject'; } } '6.1' # Windows 7 and Window Server 2008 R2 { $TypeSwitches = @{ 0x02 = 'Type'; 0x03 = 'Directory'; 0x04 = 'SymbolicLink'; 0x05 = 'Token'; 0x06 = 'Job'; 0x07 = 'Process'; 0x08 = 'Thread'; 0x09 = 'UserApcReserve'; 0x0a = 'IoCompletionReserve'; 0x0b = 'DebugObject'; 0x0c = 'Event'; 0x0d = 'EventPair'; 0x0e = 'Mutant'; 0x0f = 'Callback'; 0x10 = 'Semaphore'; 0x11 = 'Timer'; 0x12 = 'Profile'; 0x13 = 'KeyedEvent'; 0x14 = 'WindowStation'; 0x15 = 'Desktop'; 0x16 = 'TpWorkerFactory'; 0x17 = 'Adapter'; 0x18 = 'Controller'; 0x19 = 'Device'; 0x1a = 'Driver'; 0x1b = 'IoCompletion'; 0x1c = 'File'; 0x1d = 'TmTm'; 0x1e = 'TmTx'; 0x1f = 'TmRm'; 0x20 = 'TmEn'; 0x21 = 'Section'; 0x22 = 'Session'; 0x23 = 'Key'; 0x24 = 'ALPC Port'; 0x25 = 'PowerRequest'; 0x26 = 'WmiGuid'; 0x27 = 'EtwRegistration'; 0x28 = 'EtwConsumer'; 0x29 = 'FilterConnectionPort'; 0x2a = 'FilterCommunicationPort'; 0x2b = 'PcwObject'; } } '6.0' # Windows Vista and Windows Server 2008 { $TypeSwitches = @{ 0x01 = 'Type'; 0x02 = 'Directory'; 0x03 = 'SymbolicLink'; 0x04 = 'Token'; 0x05 = 'Job'; 0x06 = 'Process'; 0x07 = 'Thread'; 0x08 = 'DebugObject'; 0x09 = 'Event'; 0x0a = 'EventPair'; 0x0b = 'Mutant'; 0x0c = 'Callback'; 0x0d = 'Semaphore'; 0x0e = 'Timer'; 0x0f = 'Profile'; 0x10 = 'KeyedEvent'; 0x11 = 'WindowStation'; 0x12 = 'Desktop'; 0x13 = 'TpWorkerFactory'; 0x14 = 'Adapter'; 0x15 = 'Controller'; 0x16 = 'Device'; 0x17 = 'Driver'; 0x18 = 'IoCompletion'; 0x19 = 'File'; 0x1a = 'TmTm'; 0x1b = 'TmTx'; 0x1c = 'TmRm'; 0x1d = 'TmEn'; 0x1e = 'Section'; 0x1f = 'Session'; 0x20 = 'Key'; 0x21 = 'ALPC Port'; 0x22 = 'WmiGuid'; 0x23 = 'EtwRegistration'; 0x24 = 'FilterConnectionPort'; 0x25 = 'FilterCommunicationPort'; } } } Write-Verbose "[+] Calling NtQuerySystemInformation::SystemHandleInformation" [int]$BuffPtr_Size = 0 while ($true) { [IntPtr]$BuffPtr = [System.Runtime.InteropServices.Marshal]::AllocHGlobal($BuffPtr_Size) $SystemInformationLength = New-Object Int $CallResult = [Ntdll]::NtQuerySystemInformation(16, $BuffPtr, $BuffPtr_Size, [ref]$SystemInformationLength) # STATUS_INFO_LENGTH_MISMATCH if ($CallResult -eq 0xC0000004) { [System.Runtime.InteropServices.Marshal]::FreeHGlobal($BuffPtr) [int]$BuffPtr_Size = [System.Math]::Max($BuffPtr_Size,$SystemInformationLength) } # STATUS_SUCCESS elseif ($CallResult -eq 0x00000000) { Write-Verbose "[?] Success, allocated $BuffPtr_Size byte result buffer`n" break } # Probably: 0xC0000005 -> STATUS_ACCESS_VIOLATION else { [System.Runtime.InteropServices.Marshal]::FreeHGlobal($BuffPtr) Write-Verbose "[!] Error, NTSTATUS Value: $('{0:X}' -f ($CallResult))`n" return } } $SYSTEM_HANDLE_INFORMATION = New-Object SYSTEM_HANDLE_INFORMATION $SYSTEM_HANDLE_INFORMATION = $SYSTEM_HANDLE_INFORMATION.GetType() if ([System.IntPtr]::Size -eq 4) { $SYSTEM_HANDLE_INFORMATION_Size = 16 # This makes sense! } else { $SYSTEM_HANDLE_INFORMATION_Size = 24 # This doesn't make sense, should be 20 on x64 but that doesn't work. # Ask no questions, hear no lies! } $BuffOffset = $BuffPtr.ToInt64() $HandleCount = [System.Runtime.InteropServices.Marshal]::ReadInt32($BuffOffset) $BuffOffset = $BuffOffset + [System.IntPtr]::Size Write-Verbose "[>] Result buffer contains $HandleCount SystemHandleInformation objects" $SystemHandleArray = @() for ($i=0; $i -lt $HandleCount; $i++){ # PtrToStructure only objects we are targeting, this is expensive computation if ([System.Runtime.InteropServices.Marshal]::ReadInt32($BuffOffset) -eq $ProcID) { $SystemPointer = New-Object System.Intptr -ArgumentList $BuffOffset $Cast = [system.runtime.interopservices.marshal]::PtrToStructure($SystemPointer,[type]$SYSTEM_HANDLE_INFORMATION) $HashTable = @{ PID = $Cast.ProcessID ObjectType = if (!$($TypeSwitches[[int]$Cast.ObjectTypeNumber])) { "0x$('{0:X2}' -f [int]$Cast.ObjectTypeNumber)" } else { $TypeSwitches[[int]$Cast.ObjectTypeNumber] } HandleFlags = $FlagSwitches[[int]$Cast.Flags] Handle = "0x$('{0:X4}' -f [int]$Cast.HandleValue)" KernelPointer = if ([System.IntPtr]::Size -eq 4) { "0x$('{0:X}' -f $Cast.Object_Pointer.ToInt32())" } else { "0x$('{0:X}' -f $Cast.Object_Pointer.ToInt64())" } AccessMask = "0x$('{0:X8}' -f $($Cast.GrantedAccess -band 0xFFFF0000))" } $Object = New-Object PSObject -Property $HashTable $SystemHandleArray += $Object } $BuffOffset = $BuffOffset + $SYSTEM_HANDLE_INFORMATION_Size } Write-Verbose "[>] PID $ProcID has $($SystemHandleArray.count) handle objects" if ($($SystemHandleArray.count) -eq 0) { [System.Runtime.InteropServices.Marshal]::FreeHGlobal($BuffPtr) Write-Verbose "[!] No process handles found, exiting..`n" Return } # Set column order and auto size $SystemHandleArray | Select-Object PID,ObjectType,HandleFlags,Handle,KernelPointer,AccessMask # Free SYSTEM_HANDLE_INFORMATION array [System.Runtime.InteropServices.Marshal]::FreeHGlobal($BuffPtr) } Function Get-HandleName { [CmdLetBinding()] param( [Parameter(Mandatory=$true, ValueFromPipelineByPropertyName=$true)] [IntPtr][Int]$Handle, [Parameter(Mandatory=$true, ValueFromPipelineByPropertyName=$true)] [Alias("PID")] [UInt32]$ID, [Parameter(Mandatory=$false, ValueFromPipelineByPropertyName=$true)] [Alias("ObjectType")] [String]$Type ) Process { $duplicatedHandle = [IntPtr]::Zero $processHandle = [Kernel32]::OpenProcess([ProcessAccessFlags]::DuplicateHandle, $true, $ID) $process = [Kernel32]::GetCurrentProcess() $options = [DuplicateOptions]::DUPLICATE_SAME_ACCESS [bool]$success = [Kernel32]::DuplicateHandle($processHandle, $handle, $process, [ref]$duplicatedHandle, 0, $false, $options) [Kernel32]::CloseHandle($processHandle) | Out-Null if(!$success) { return } $dummy = 0 $length = [Runtime.InteropServices.Marshal]::SizeOf([type][OBJECT_NAME_INFORMATION]) + 256 [IntPtr]$buffer = [Runtime.InteropServices.Marshal]::AllocHGlobal($length) $status = [NTDLL]::NtQueryObject( $duplicatedHandle, [OBJECT_INFORMATION_CLASS]::ObjectNameInformation, $buffer, $length, [ref]$dummy ) if ($status -eq [NtStatus]::Success) { $temp = [Runtime.InteropServices.Marshal]::PtrToStructure($buffer, [type][OBJECT_NAME_INFORMATION]) $rName = $temp.Name.ToString() if($rName) { $Name = ConvertTo-RegularFileName $rName [PSCustomObject]@{ Handle = "0x{0:X}" -f [long]$Handle ID = $ID Type = $Type Name = $Name } } } [Runtime.InteropServices.Marshal]::FreeHGlobal($buffer) | Out-Null [Kernel32]::CloseHandle($duplicatedHandle) | Out-Null } }
Пример вывода:
Get-Handles -ProcID (Get-Process FoxitReader).ID -Verbose | Get-HandleName
$h = Get-Handles -ProcID (Get-Process FoxitReader).ID | Get-HandleName $h | Where Name -match "pdf"
Get-HandleName.ps1 — https://github.com/PoshKazun/Garbage/blob/master/Get-HandleName.ps1
One thing that annoys me no end about Windows is the old sharing violation error. Often you can’t identify what’s holding it open. Usually it’s just an editor or explorer just pointing to a relevant directory but sometimes I’ve had to resort to rebooting my machine.
Any suggestions on how to find the culprit?
asked May 1, 2009 at 0:47
6
I’ve had success with Sysinternals Process Explorer. With this, you can search to find what process(es) have a file open, and you can use it to close the handle(s) if you want. Of course, it is safer to close the whole process. Exercise caution and judgement.
To find a specific file, use the menu option Find->Find Handle or DLL...
Type in part of the path to the file. The list of processes will appear below.
If you prefer command line, Sysinternals suite includes command line tool Handle, that lists open handles.
Examples
c:Program FilesSysinternalsSuite>handle.exe |findstr /i "e:"
(finds all files opened from drivee:
«c:Program FilesSysinternalsSuite>handle.exe |findstr /i "file-or-path-in-question"
bjoster
4,6535 gold badges23 silver badges33 bronze badges
answered May 1, 2009 at 1:03
EddieEddie
11.4k8 gold badges37 silver badges48 bronze badges
18
You can use the Resource Monitor for this which comes built-in with Windows 7, 8, and 10.
- Open Resource Monitor, which can be found
- By searching for Resource Monitor or resmon.exe in the start menu, or
- As a button on the Performance tab in your Task Manager
- Go to the CPU tab
- Use the search field in the Associated Handles section
- See blue arrow in screen shot below
When you’ve found the handle, you can identify the process by looking at the Image and/or PID column.
You can then try to close the application as you normally would, or, if that’s not possible, just right-click the handle and kill the process directly from there. Easy peasy!
Copied from my original answer: https://superuser.com/a/643312/62
answered Sep 10, 2013 at 11:48
SvishSvish
6,91715 gold badges38 silver badges45 bronze badges
13
Just be very careful with closing handles; it’s even more dangerous than you’d think, because of handle recycling — if you close the file handle, and the program opens something else, that original file handle you closed may be reused for that «something else.» And now guess what happens if the program continues, thinking it is working on the file (whose handle you closed), when in fact that file handle is now pointing to something else.
see Raymond Chen’s post on this topic
Suppose a search index service has a file open for indexing but has
gotten stuck temporarily and you want to delete the file, so you
(unwisely) force the handle closed. The search index service opens its
log file in order to record some information, and the handle to the
deleted file is recycled as the handle to the log file. The stuck
operation finally completes, and the search index service finally gets
around to closing that handle it had open, but it ends up unwittingly
closing the log file handle.The search index service opens another
file, say a configuration file for writing so it can update some
persistent state. The handle for the log file gets recycled as the
handle for the configuration file. The search index service wants to
log some information, so it writes to its log file. Unfortunately, the
log file handle was closed and the handle reused for its configuration
file. The logged information goes into the configuration file,
corrupting it.Meanwhile, another handle you forced closed was reused
as a mutex handle, which is used to help prevent data from being
corrupted. When the original file handle is closed, the mutex handle
is closed and the protections against data corruption are lost. The
longer the service runs, the more corrupted its indexes become.
Eventually, somebody notices the index is returning incorrect results.
And when you try to restart the service, it fails because its
configuration files have been corrupted.You report the problem to the
company that makes the search index service and they determine that
the index has been corrupted, the log file has mysteriously stopped
logging, and the configuration file was overwritten with garbage. Some
poor technician is assigned the hopeless task of figuring out why the
service corrupts its indexes and configuration files, unaware that the
source of the corruption is that you forced a handle closed.
answered May 30, 2009 at 17:04
Mark SowulMark Sowul
1,8391 gold badge11 silver badges14 bronze badges
10
Try the openfiles command.
You might have to enable listing of localy opened files by running openfiles /local on
and rebooting.
answered May 1, 2009 at 1:18
John FouhyJohn Fouhy
1,1317 silver badges4 bronze badges
7
I’ve used Handle with success to find such processes in the past.
answered May 1, 2009 at 0:52
Greg HewgillGreg Hewgill
6,8293 gold badges30 silver badges26 bronze badges
2
Just to clarify, this is more likely to be a result of misbehaving 3rd party apps not using the CreateFile API call correctly than it is to be anything in Windows itself. Perhaps it’s a consequence of the design of CreateFile, but done is done and we can’t go back.
Basically when opening a file in a Windows program you have the option to specify a flag that allows shared access. If you don’t specify the flag, the program takes exclusive access of the file.
Now, if Explorer seems to be the culprit here, it may be the case that that’s just on the surface, and that the true culprit is something that installs a shell extension that opens all files in a folder for it’s own purposes but is either too gung-ho in doing so, or that doesn’t clean up properly after itself. Symantec AV is something I’ve seen doing this before, and I wouldn’t be surprised if other AV programs were also to blame. Source control plug-ins may also be at fault.
So not really an answer, but just some advice to not always blame Windows for what may be a badly written 3rd party program (something that can also happen on any other OS which has implicit file locking, but any unix based OS has shared access by default).
answered Oct 12, 2009 at 14:27
Maximus MinimusMaximus Minimus
8,9872 gold badges22 silver badges36 bronze badges
2
On a remote server, when you’re checking on a network share, something as simple as the Computer Management console can display this information and close the file.
answered May 1, 2009 at 1:01
1
Apropos Explorer holding a file open: «When this happens on a file you need to delete, you have the choice of forcing the handle closed, or rebooting.»
You can just end Explorer.
If this is a one-time thing (Explorer does not normally hold this file open) then I would guess logging off and logging back on will do the trick.
Otherwise, kill the desktop Explorer process and do what you want while it’s gone. First start a copy of cmd.exe (you need a UI to do your intended cleanup). Make sure there are no non-desktop Explorers running. Then kill the last Explorer with, e.g., Task Manager. Do what you want in the command prompt. Finally, run Explorer from the command prompt, and it will become the desktop.
I’d guess there may be some residual unpleasantness if some systray programs can’t deal with the shell restarting.
answered Jun 3, 2009 at 14:01
1
Who Lock Me works well and keeps people amused with the name!
yagmoth555♦
16.7k4 gold badges29 silver badges50 bronze badges
answered May 6, 2009 at 0:43
Generic ErrorGeneric Error
5933 gold badges8 silver badges16 bronze badges
2
Files can be locked by local processes (unlocker is the tool to use) and by file access that comes in through shares.
There is a built-in function in Windows that shows you what files on the local computer are open/locked by remote computer (which has the file open through a file share):
* Select "Manage Computer" (Open "Computer Management")
* click "Shared Folders"
* choose "Open Files"
There you can even close the file forcefully.
answered Oct 12, 2009 at 12:53
Dirk PaesslerDirk Paessler
9141 gold badge7 silver badges15 bronze badges
With Process Hacker you can identify what processes are holding your files easily:
answered Oct 12, 2016 at 23:07
Ivan KochurkinIvan Kochurkin
1831 gold badge1 silver badge6 bronze badges
The above upvoted answers cover situations where a program process is holding the file handle open, which (fortunately) is most of the time — however in some cases (as is occurring on this system at the moment), the system itself holds a file handle open.
You can identify this situation by following the instructions to find the file handle holding process with process explorer above, and noting that the process name is listed as ‘system’, or by following the the instructions using resource monitor and noting that no image is shown having a filehandle open on your file of interest (Although obviously something does as you can’t edit/delete etc the file).
If that happens, your option (so far as I’m aware) is to restart — or forget about doing anything with that file.
answered May 16, 2017 at 0:51
BlairBlair
312 bronze badges
I got turned on to the Free Extended Task Manager a while ago by Jeremy Zawodny’s blog, and it’s great for tracking down further info on processes too. +1 for Process Explorer as above, too, especially for killing processes that the standard Task Manager won’t end.
answered May 16, 2009 at 20:16
nedmnedm
5,6205 gold badges32 silver badges52 bronze badges
There have new PowerToys available from Microsoft.
File Locksmith
utility for Windows | Microsoft Learn
https://learn.microsoft.com/en-us/windows/powertoys/file-locksmith
After installing PowerToys, right-click on one or more selected files in File Explorer, and then select What’s using this file? from the menu.
answered Nov 21, 2022 at 6:54
Ivan ChauIvan Chau
2411 silver badge12 bronze badges
There is a tool FILEMON and shows open files and handles. Its hard to keep up with its display if you watch it live, it does so quickly. But you can stop it from displaying live and you can watch all file open/write activity. Now owned by Microsoft but originally by Sysinternals
answered May 27, 2010 at 16:15
1
You can also do it programmatically by leveraging on the NTDLL/KERNEL32 Windows API. E.g. have a look at the following code in Python:
import ctypes
from ctypes import wintypes
path = r"C:temptest.txt"
# -----------------------------------------------------------------------------
# generic strings and constants
# -----------------------------------------------------------------------------
ntdll = ctypes.WinDLL('ntdll')
kernel32 = ctypes.WinDLL('kernel32', use_last_error=True)
NTSTATUS = wintypes.LONG
INVALID_HANDLE_VALUE = wintypes.HANDLE(-1).value
FILE_READ_ATTRIBUTES = 0x80
FILE_SHARE_READ = 1
OPEN_EXISTING = 3
FILE_FLAG_BACKUP_SEMANTICS = 0x02000000
FILE_INFORMATION_CLASS = wintypes.ULONG
FileProcessIdsUsingFileInformation = 47
LPSECURITY_ATTRIBUTES = wintypes.LPVOID
ULONG_PTR = wintypes.WPARAM
# -----------------------------------------------------------------------------
# create handle on concerned file with dwDesiredAccess == FILE_READ_ATTRIBUTES
# -----------------------------------------------------------------------------
kernel32.CreateFileW.restype = wintypes.HANDLE
kernel32.CreateFileW.argtypes = (
wintypes.LPCWSTR, # In lpFileName
wintypes.DWORD, # In dwDesiredAccess
wintypes.DWORD, # In dwShareMode
LPSECURITY_ATTRIBUTES, # In_opt lpSecurityAttributes
wintypes.DWORD, # In dwCreationDisposition
wintypes.DWORD, # In dwFlagsAndAttributes
wintypes.HANDLE) # In_opt hTemplateFile
hFile = kernel32.CreateFileW(
path, FILE_READ_ATTRIBUTES, FILE_SHARE_READ, None, OPEN_EXISTING,
FILE_FLAG_BACKUP_SEMANTICS, None)
if hFile == INVALID_HANDLE_VALUE:
raise ctypes.WinError(ctypes.get_last_error())
# -----------------------------------------------------------------------------
# prepare data types for system call
# -----------------------------------------------------------------------------
class IO_STATUS_BLOCK(ctypes.Structure):
class _STATUS(ctypes.Union):
_fields_ = (('Status', NTSTATUS),
('Pointer', wintypes.LPVOID))
_anonymous_ = '_Status',
_fields_ = (('_Status', _STATUS),
('Information', ULONG_PTR))
iosb = IO_STATUS_BLOCK()
class FILE_PROCESS_IDS_USING_FILE_INFORMATION(ctypes.Structure):
_fields_ = (('NumberOfProcessIdsInList', wintypes.LARGE_INTEGER),
('ProcessIdList', wintypes.LARGE_INTEGER * 64))
info = FILE_PROCESS_IDS_USING_FILE_INFORMATION()
PIO_STATUS_BLOCK = ctypes.POINTER(IO_STATUS_BLOCK)
ntdll.NtQueryInformationFile.restype = NTSTATUS
ntdll.NtQueryInformationFile.argtypes = (
wintypes.HANDLE, # In FileHandle
PIO_STATUS_BLOCK, # Out IoStatusBlock
wintypes.LPVOID, # Out FileInformation
wintypes.ULONG, # In Length
FILE_INFORMATION_CLASS) # In FileInformationClass
# -----------------------------------------------------------------------------
# system call to retrieve list of PIDs currently using the file
# -----------------------------------------------------------------------------
status = ntdll.NtQueryInformationFile(hFile, ctypes.byref(iosb),
ctypes.byref(info),
ctypes.sizeof(info),
FileProcessIdsUsingFileInformation)
pidList = info.ProcessIdList[0:info.NumberOfProcessIdsInList]
print(pidList)
answered Nov 10, 2022 at 13:22
RobertRobert
1214 bronze badges
Как узнать, какой процесс блокирует файл или папку в Windows
Как я могу узнать, какой процесс блокирует файл или папку в Windows? Например, при попытке удалить папку Windows сообщает следующее:
Операция не может быть завершена, так как эти папка или файл открыты в другой программе. Закройте папку или файл и повторите попытку.
Такая же ошибка может возникнуть при переименовании или удаления как папки, так и файла. Но как узнать, какая программа или приложение в настоящее время использует его и не позволяет удалить файл или папку?
Имеется сразу несколько способов и программ чтобы найти процессы и программы, которые открыли файл.
1. Монитор ресурсов
Для поиска программы или процесса, открывшей файл, вы можете использовать Монитор ресурсов (Resource Monitor), который встроен в Windows 7, 8 и 10.
Откройте Монитор ресурсов, это можно сделать несколькими способами:
- В поле для поиска введите «Монитор ресурсов» или resmon.exe:
- Или в Диспетчере задач перейдите на вкладку «Производительность» и найдите кнопку «Открыть монитор ресурсов»:
В Мониторе ресурсов перейдите на вкладку ЦП (CPU). Используйте поле поиска в разделе «Связанные дескрипторы»
В результатах поиска в столбце «Образ» вы увидите, какая программа запустила процесс, блокирующий файл.
Здесь же вы можете кликнуть правой кнопкой мыши по любому найденному процессу и нажать «Завершить процесс», чтобы закрыть программу, блокирующую файл.
2. Process Explorer
Process Explorer — это официальная программа от Microsoft/SysInternals, которую можно скачать по ссылке: https://download.sysinternals.com/files/ProcessExplorer.zip
Перейдите в Find → Handle or DLL.
В текстовом поле «Handle or DLL substring:» введите путь до файла или папки. Будут показаны все процессы, которые имеют открытый обработчик на этот файл.
3. OpenedFilesView
OpenedFilesView это бесплатная программа не требующая установки, она покажет все открытые файлы, имеется возможность искать по имени или пути файла:
4. LockHunter
LockHunter — это надёжная программа для разблокировки файлов.
Это бесплатный инструмент для удаления файлов, заблокированных неизвестным процессом. LockHunter полезен для борьбы с вредоносными программами и другими программами, которые блокируют файлы без причины. В отличие от других подобных инструментов, он удаляет файлы в корзину, поэтому вы можете восстановить их, если удалили по ошибке.
Узнайте, какой процесс блокирует файл или папку в Windows
Как узнать, какой процесс блокирует файл или папку в Windows?
Например, при попытке удалить папку Windows сообщает об этом:
Действие не может быть выполнено, потому что папка открыта в другой программе
Случается то же самое с файлом, но как узнать, какая программа или приложение в настоящее время его использует и не позволяет мне удалить файл или папку?
9 ответов
Для Windows 7, 8 и 10 для этого можно использовать встроенный Resource Monitor .
- Откройте Монитор ресурсов , который можно найти
- При поиске resmon.exe в меню «Пуск» или
- В качестве кнопки на вкладке Производительность в Диспетчере задач
- Откройте вкладку CPU и используйте поле поиска в разделе Связанные ручки
- Указывается синей стрелкой на скриншоте ниже
Если это не очевидно, когда вы нашли дескриптор, вы можете определить процесс, посмотрев на столбец Image и /или PID.
Затем вы можете закрыть приложение, если это возможно, или просто щелкнуть правой кнопкой мыши по строке, и вы получите возможность убить процесс прямо там. Легкий peasy!
Проводник процессов Microsoft /SysInternals — перейдите в Find> Find Handle или DLL. В текстовом поле «Ручка или DLL подстрока:» введите путь к файлу (например, «C: path to file.txt») и нажмите «Поиск». Все процессы, у которых есть открытый дескриптор этого файла, должны быть перечислены.
WhoLockMe — расширение проводника, которое добавляет пункт меню правой кнопки мыши
N.B. WhoLockMe, похоже, не работает с Win 10 (по крайней мере, мне не удалось зарегистрировать его ни в одной из 32- или 64-разрядных версий regsvr32.exe).
Вы когда-нибудь задавались вопросом, какая программа имеет определенный файл или каталог? Теперь вы можете это выяснить.
Чтобы узнать, какой процесс использует определенный файл, выполните следующие действия:
Перейдите в Найти , Найти Handle или DLL .. или просто нажмите Ctrl + F .
LockHunter может разблокировать любые обработчики, которые могут заблокировать ваши файлы или папки. В отличие от подобных автострад, он поддерживает как 32, так и 64-битные Windows.
- Показывает процессы, блокирующие файл или папку
- Позволяет разблокировать, удалить, скопировать или переименовать заблокированный файл
- Позволяет убить процесс блокировки
- Позволяет удалить процессы блокировки с жесткого диска.
- Интегрируется в меню Проводника
- Он удаляет файлы в корзину, поэтому вы можете их восстановить, если они были удалены по ошибке.
- Поддержка 32-разрядной и 64-битной Windows
EMCO UnlockIT может идентифицировать процесс, который заблокировал файл, а также разблокировать файл, чтобы вы может удалить /отредактировать /переместить его. Программа полностью бесплатна, хотя более новая версия немного медленнее и более раздутой, чем оригинал (у которого был простой, неподтвержденный графический интерфейс, но загружался практически мгновенно и без раздражающего заставки). Кроме того, оригинальная версия используется для автоматического всплытия всякий раз, когда вы вызываете ошибку, которая позволяет вам мгновенно разблокировать файл и выполнить операцию, которую вы пытаетесь выполнить.
Тем не менее, UnlockIT — невероятно полезная программа, которая обеспечивает базовые функции, которые критически отсутствуют в Windows. Это один из стандартных наборов инструментов, которые я устанавливаю на всех компьютерах Windows, над которыми я работаю.
Вот мое открытие & Решение.
Кстати, ни один из вышеперечисленных ответов не решил мою проблему.
Я даже пытался использовать UNLOCKER, который оказался бесполезным.
Моя проблема была в том, что Memeo Autosync Backup
По-видимому, этот процесс резервного копирования оставляет достаточно «файла-призрака». Этот «призрак, как файл», будет отображаться всякий раз, когда я буду ALT-TAB на моем компьютере (Windows Professional XP), то есть я увижу, что в моей TASK BAR запускаются две программы MS Excel, когда я только ОДИН был видимым.
Я столкнулся с этим решением, когда подумал, что это могла быть защита SYMANTEC Endpoint (Anti-Virus); и отключил программу. Однако я продолжал получать сообщение об ошибке:
невозможно удалить (файл LARGE.xls): он используется другим человеком или программой. Закройте все программы, которые могут использовать этот файл, и повторите попытку.
Впоследствии я продолжал видеть уведомление Memeo о «синхронизации» и ВЫКЛЮЧИТЬ программу.
Затем NO NO ERROR.
Для вас это может быть ЛЮБОЙ из этих фоновых сейвов.
Если вы не знаете программу, которую он использует, вы можете перейти в «Мой компьютер»; щелкните правой кнопкой мыши; выберите «Управление». В разделе «Системные инструменты»> Общие папки> Откройте файлы, вы сможете увидеть пользователя, который заблокировал файл. Здесь вы можете закрыть файл, а затем выполнить задачу переименования или удаления файла. Надеюсь, что это поможет
Дополнительная возможность, просто чтобы сэкономить людям время, которое я потратил:
В более старых версиях Windows вы можете получить «Доступ запрещен — у вас могут не быть прав или файл может быть использован». Если вы обнаружите через Process Explorer, что файлы, по сути, не открыты кем-либо, есть вероятность, что проблема связана с безопасностью. Используя учетную запись администратора, выберите файлы в проводнике, щелкните правой кнопкой мыши и выберите «Свойства», «Безопасность», «Дополнительно», «Владелец». Вероятность того, что файлы принадлежат учетной записи, которая больше не существует или больше не может быть проверена, существует (из-за изменения настроек доверия Active Directory).
Узнайте, какой процесс блокирует файл или папку в Windows
Как я могу узнать, какой процесс блокирует файл или папку в Windows?
Например, при попытке удалить папку Windows сообщает об этом:
Действие не может быть завершено, потому что папка открыта в другой программе
Происходит то же самое с файлом, но как мне узнать, какая программа или приложение использует его в настоящее время и не позволяет мне удалить файл или папку?
В openfiles команде должна быть включена поддержка локальных файлов при запуске openfiles /local on и перезапуске.
Для этого вы можете использовать Resource Monitor, который встроен в Windows 7, 8 и 10.
- Откройте Resource Monitor , который можно найти
- Выполнив поиск Resource Monitor или resmon.exe в меню «Пуск», или
- Как кнопка на вкладке « Производительность » в вашем диспетчере задач
- Перейти на вкладку CPU
- Используйте поле поиска в разделе « Связанные дескрипторы »
- Смотрите синюю стрелку на снимке экрана ниже
Найдя дескриптор, вы можете определить процесс, посмотрев на столбец «Изображение» и / или «PID».
Затем вы можете попытаться закрыть приложение, как обычно, или, если это невозможно, просто щелкнуть правой кнопкой мыши по дескриптору и завершить процесс прямо оттуда. Очень просто!
Microsoft / SysInternals Process Explorer — выберите «Найти»> «Найти дескриптор» или «DLL». В текстовом поле «Обрабатывать или подстрока DLL:» введите путь к файлу (например, «C: path to file.txt») и нажмите «Поиск». Все процессы, которые имеют открытый дескриптор этого файла, должны быть перечислены.
WhoLockMe — расширение для проводника, которое добавляет контекстное меню
NB WhoLockMe по- видимому, не работает с Win 10 ( по крайней мере , я не смог зарегистрировать его с любым из 32- или 64-разрядных версий regsvr32.exe).
Посмотрите на Process Explorer ( procexp.exe ).
Из его введения:
Задумывались ли вы, какая программа имеет определенный файл или каталог открыт? Теперь вы можете узнать.
Чтобы узнать, какой процесс использует определенный файл, выполните следующие действия:
Зайдите в Find , Find Handle или DLL .. или просто нажмите Ctrl + F .
Введите имя файла и нажмите Поиск .
Process Explorer перечислит все процессы, которые имеют дескриптор открытого файла. Нажмите на запись, чтобы сфокусировать процесс в главном окне.
При желании вы можете даже закрыть ручку вручную через нижнюю панель ( Ctrl + L ):
LockHunter может разблокировать любые обработчики, которые могли заблокировать ваши файлы или папки. В отличие от аналогичных бесплатных программ, он поддерживает как 32-разрядные, так и 64-разрядные версии Windows.
- Показывает процессы, блокирующие файл или папку
- Позволяет разблокировать, удалить, скопировать или переименовать заблокированный файл
- Позволяет убить процесс блокировки
- Позволяет удалить процессы блокировки с жесткого диска
- Интегрируется в меню Проводника
- Он удаляет файлы в корзину, поэтому вы можете восстановить их, если удалили по ошибке
- Поддерживает как 32, так и 64-битную Windows
EMCO UnlockIT может идентифицировать процесс, который заблокировал файл, а также разблокировать файл, чтобы вы могли удалить / отредактировать / переместить его. Программа полностью бесплатна, хотя более новая версия немного медленнее и более раздутая, чем оригинал (который имел простой, некорпорированный графический интерфейс, но загружался практически мгновенно и без раздражающего заставки). Кроме того, исходная версия использовалась для автоматического всплывающего сообщения при возникновении упомянутой ошибки, что позволяет мгновенно разблокировать файл и выполнить операцию, которую вы пытались выполнить.
Тем не менее, UnlockIT — невероятно полезная программа, которая предоставляет базовую функциональность, которая критически отсутствует в Windows. Это один из стандартных наборов утилит, который я устанавливаю на все компьютеры с Windows, на которых работаю.
Здесь было мое открытие и решение.
Кстати, ни один из приведенных выше ответов не решил мою проблему.
Я даже пытался использовать UNLOCKER, который оказался бесполезным.
У меня проблема была с Memeo Autosync Backup
По-видимому, этот процесс резервного копирования оставляет достаточно «призрачного файла». Этот «призрачный файл» появлялся всякий раз, когда я запускал ALT-TAB на моем компьютере (Windows Professional XP), то есть я видел ДВА программы MS Excel, работающие, когда у меня была только ОДНА видимая, на панели задач.
Я столкнулся с этим решением, когда подумал, что это может быть защита от вирусов SYMANTEC Endpoint (Anti-Virus); и отключил программу. Тем не менее, я продолжал получать сообщение об ошибке:
невозможно удалить (файл LARGE.xls): он используется другим пользователем или программой. Закройте все программы, которые могут использовать этот файл, и повторите попытку.
Впоследствии я продолжал видеть уведомление Memeo о «синхронизации» и выход из программы.