Microsoft MVP성태의 닷넷 이야기
.NET Framework: 335. C# - (핸들을 이용하여) 모든 열린 파일을 열람 [링크 복사], [링크+제목 복사],
조회: 33613
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일

(시리즈 글이 5개 있습니다.)
.NET Framework: 335. C# - (핸들을 이용하여) 모든 열린 파일을 열람
; https://www.sysnet.pe.kr/2/0/1338

.NET Framework: 525. C# - 닷넷에서 프로세스가 열고 있는 파일 목록을 구하는 방법
; https://www.sysnet.pe.kr/2/0/10833

.NET Framework: 870. C# - 프로세스의 모든 핸들을 열람
; https://www.sysnet.pe.kr/2/0/12080

.NET Framework: 877. C# - 프로세스의 모든 핸들을 열람 - 두 번째 이야기
; https://www.sysnet.pe.kr/2/0/12107

.NET Framework: 902. C# - 프로세스의 모든 핸들을 열람 - 세 번째 이야기
; https://www.sysnet.pe.kr/2/0/12195




C# - (핸들을 이용하여) 모든 열린 파일을 열람

아시는 것처럼, .NET Framework에서는 기본적으로 프로세스에 열려진 '핸들' 목록을 얻을 수 있는 방법이 없습니다. 사실, 저수준의 핸들이라는 개념 자체가 닷넷에서는 감춰지므로 이해가 됩니다.

대신, P/Invoke를 이용하면 C/C++에서 했던 것과 동일하게 구현을 할 수 있습니다. 마침, Codeplex에서 이와 관련된 소스 코드를 찾아냈는데요.

DetectOpenFiles.cs - CodePlex
; https://vmccontroller.svn.codeplex.com/svn/VmcController/VmcServices/DetectOpenFiles.cs

한 가지 아쉬운 점이라면, 해당 코드가 32비트에서만 동작할 뿐 64비트에서 실행하면 다음과 같은 예외를 발생시킵니다.

System.OverflowException was unhandled by user code
  Message=Arithmetic operation resulted in an overflow.
  Source=mscorlib
  StackTrace:
       at System.IntPtr.op_Explicit(IntPtr value)
       at WebApplication1.DetectOpenFiles.OpenFiles.<GetEnumerator>d__0.MoveNext() in d:\...\WebApplication1\DetectOpenFiles.cs:line 273
       at WebApplication1.WebForm1.Page_Load(Object sender, EventArgs e) in d:\...\WebApplication1\WebForm1.aspx.cs:line 19
       at System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e)
       at System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e)
       at System.Web.UI.Control.OnLoad(EventArgs e)
       at System.Web.UI.Control.LoadRecursive()
       at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
  InnerException: 

다행히 64비트 포팅이 어렵지는 않습니다. 우선, SYSTEM_HANDLE_ENTRY에서 포인터 값이 기존에는 int로 표현되어 있는 것을 IntPtr로 수정해야 합니다.

[StructLayout(LayoutKind.Sequential)]
private struct SYSTEM_HANDLE_ENTRY
{
    public int OwnerPid;
    public byte ObjectType;
    public byte HandleFlags;
    public short HandleValue;
    public IntPtr ObjectPointer;
    public int AccessMask;
}

그 외, handlCount를 읽어들이는 부분에서 4byte가 아닌 8byte를 읽어야 하고,


long handleCount = 0;
if (IntPtr.Size == 4)
{
    handleCount = Marshal.ReadInt32(ptr);
}
else
{
    handleCount = Marshal.ReadInt64(ptr);
}

포인터 처리에 대해서 "(int)ptr"와 같은 표현을 "ptr.ToInt64()"와 같이 바꿔야 합니다.

기타 결정적인 차이점이, "GetFileNameFromHandle" 메서드 안에서 발생하는데요.

private static bool GetFileNameFromHandle(IntPtr handle, out string fileName)
{
    ...[생략]...
    NT_STATUS ret = NativeMethods.NtQueryObject(handle, OBJECT_INFORMATION_CLASS.ObjectNameInformation, ptr, length, out length);
    if (ret == NT_STATUS.STATUS_BUFFER_OVERFLOW)
    {
        ...[생략]...
        ret = NativeMethods.NtQueryObject(handle, OBJECT_INFORMATION_CLASS.ObjectNameInformation, ptr, length, out length);
    }
    if (ret == NT_STATUS.STATUS_SUCCESS)
    {
        fileName = Marshal.PtrToStringUni((IntPtr)((int)ptr + 8), (length - 9) / 2);
        return fileName.Length != 0;
    }
    ...[생략]...
}

위에서 파일 이름을 가져오는 포인터 옵셋값(+8)이 64비트에서는 바뀐다는 점입니다. 정확한 위치를 알기 위해 64비트로 해당 프로그램을 실행시킨 후 ptr.ToInt64() 값을 알아내야 합니다. 디버거의 "Watch" 창을 이용하여 알아낸 값이 "0x00000000022b0930"라고 가정하고 진행했을 때, 이 값을 메모리 윈도우(Ctrl+D,Y) 창에서 확인해 봅니다. 제 경우에는 다음과 같이 나왔습니다.

list_all_file_handle_1.png

보시는 것처럼, 일정 바이트 후에 "\Device\HarddiskVolume2\Windows\assembly\pubpol60.dat"라는 (유니코드) 문자열이 확인되는데, 시작 바이트가 16바이트 이후임을 계산해 낼 수 있습니다. 최종적으로 이를 반영하면 다음과 같은 코드가 나옵니다.

if (IntPtr.Size == 4)
{
    fileName = Marshal.PtrToStringUni((IntPtr)((int)ptr + 8), (length - 9) / 2);
}
else
{
    IntPtr namePtr = new IntPtr(ptr.ToInt64() + 16);
    fileName = Marshal.PtrToStringUni(namePtr);
}

옵셋값은 테스트 결과 다행히 Windows 2003부터 Windows 8까지 전혀 변함없이 사용할 수 있었습니다. 하지만, 코드를 실행하는 권한에 따라서는 범위가 달라지므로 사용 시 이를 감안해야 합니다.

첨부한 프로젝트는 위의 코드를 테스트할 수 있는 간략한 윈폼 프로젝트입니다.

list_all_file_handle_2.png




[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]







[최초 등록일: ]
[최종 수정일: 6/22/2023]

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 



2017-09-01 07시45분
[최의현] 해당 리스트 Close하려면 혹시 어떻게 해야 하는지 아시나요?
[guest]
2017-09-01 08시30분
[최의현] Process Explorer 에서 아래쪽 패널(하위핸들 - file, Event 등등)에 있는 핸들을 Close시킬 수 있더라구요. 우클릭 - Close Handle
같은 기능을 닷넷에서 구현하려는데 잘 안되어서 자문 구하고자 왔습니다.
[guest]
2017-09-01 03시40분
Close는 Win32 API의 CloseHandle을 이용하시면 PInvoke로 호출하시면 됩니다. 참고로, Process Explorer의 경우 다른 프로세스의 핸들을 닫는 경우인데요. 이럴 때는 반드시 그 프로세스 공간 내에서 실행된 코드를 통해 CloseHandle을 호출해야 합니다. 아마 Process Explorer는 그렇게 했을 것입니다.
정성태
2017-09-04 05시18분
[최의현] 아 그 프로세스 공간에서 해야되는군요.
그걸 놓치고 있었네요.
고유 핸들값이 따로 있는줄 알고 삽질 했네요.
덕분에 잘 배워갑니다. 감사합니다.
[guest]
2019-10-17 07시15분
C# - 닷넷에서 프로세스가 열고 있는 파일 목록을 구하는 방법
; http://www.sysnet.pe.kr/2/0/10833
정성태
2020-03-16 11시46분
해당 프로세스 공간에 침입하지 않고도 다른 프로세스의 핸들을 닫는 방법이 아래의 글에 나와 있습니다.

How can I close a handle in another process?
; https://scorpiosoftware.net/2020/03/15/how-can-i-close-a-handle-in-another-process/

간단하게 정리해 보면, 다른 프로세스의 핸들을 DUPLICATE_CLOSE_SOURCE 옵션을 적용해 DuplicateHandle을 호출한 후 얻은 핸들 값을 CloseHandle 시키면 됩니다.
정성태

... 76  [77]  78  79  80  81  82  83  84  85  86  87  88  89  90  ...
NoWriterDateCnt.TitleFile(s)
12042정성태10/26/201918690오류 유형: 573. OneDrive 하위에 위치한 Documents, Desktop 폴더에 대한 권한 변경 시 "Unable to display current owner"
12041정성태10/23/201920243오류 유형: 572. mstest.exe - The load test results database could not be opened.
12040정성태10/23/201920807오류 유형: 571. Unhandled Exception: System.Net.Mail.SmtpException: Transaction failed. The server response was: 5.2.0 STOREDRV.Submission.Exception:SendAsDeniedException.MapiExceptionSendAsDenied
12039정성태10/22/201917729스크립트: 16. cmd.exe의 for 문에서는 ERRORLEVEL이 설정되지 않는 문제
12038정성태10/17/201918279오류 유형: 570. SQL Server 2019 RC1 - SQL Client Connectivity SDK 설치 오류
12037정성태10/15/201925892.NET Framework: 867. C# - Encoding.Default 값을 바꿀 수 있을까요?파일 다운로드1
12036정성태10/14/201927215.NET Framework: 866. C# - 고성능이 필요한 환경에서 GC가 발생하지 않는 네이티브 힙 사용파일 다운로드1
12035정성태10/13/201920564개발 환경 구성: 461. C# 8.0의 #nulable 관련 특성을 .NET Framework 프로젝트에서 사용하는 방법 [2]파일 다운로드1
12034정성태10/12/201920091개발 환경 구성: 460. .NET Core 환경에서 (프로젝트가 아닌) C# 코드 파일을 입력으로 컴파일하는 방법 [1]
12033정성태10/11/201924514개발 환경 구성: 459. .NET Framework 프로젝트에서 C# 8.0/9.0 컴파일러를 사용하는 방법
12032정성태10/8/201920132.NET Framework: 865. .NET Core 2.2/3.0 웹 프로젝트를 IIS에서 호스팅(Inproc, out-of-proc)하는 방법 - AspNetCoreModuleV2 소개
12031정성태10/7/201918085오류 유형: 569. Azure Site Extension 업그레이드 시 "System.IO.IOException: There is not enough space on the disk" 예외 발생
12030정성태10/5/201925169.NET Framework: 864. .NET Conf 2019 Korea - "닷넷 17년의 변화 정리 및 닷넷 코어 3.0" 발표 자료 [1]파일 다운로드1
12029정성태9/27/201925367제니퍼 .NET: 29. Jennifersoft provides a trial promotion on its APM solution such as JENNIFER, PHP, and .NET in 2019 and shares the examples of their application.
12028정성태9/26/201920982.NET Framework: 863. C# - Thread.Suspend 호출 시 응용 프로그램 hang 현상을 해결하기 위한 시도파일 다운로드1
12027정성태9/26/201915629오류 유형: 568. Consider app.config remapping of assembly "..." from Version "..." [...] to Version "..." [...] to solve conflict and get rid of warning.
12026정성태9/26/201921952.NET Framework: 862. C# - Active Directory의 LDAP 경로 및 정보 조회
12025정성태9/25/201920242제니퍼 .NET: 28. APM 솔루션 제니퍼, PHP, .NET 무료 사용 프로모션 2019 및 적용 사례 (8) [1]
12024정성태9/20/201922184.NET Framework: 861. HttpClient와 HttpClientHandler의 관계 [2]
12023정성태9/18/201922635.NET Framework: 860. ServicePointManager.DefaultConnectionLimit와 HttpClient의 관계파일 다운로드1
12022정성태9/12/201926177개발 환경 구성: 458. C# 8.0 (Preview) 신규 문법을 위한 개발 환경 구성 [3]
12021정성태9/12/201942261도서: 시작하세요! C# 8.0 프로그래밍 [4]
12020정성태9/11/201925230VC++: 134. SYSTEMTIME 값 기준으로 특정 시간이 지났는지를 판단하는 함수
12019정성태9/11/201918936Linux: 23. .NET Core + 리눅스 환경에서 Environment.CurrentDirectory 접근 시 주의 사항
12018정성태9/11/201917785오류 유형: 567. IIS - Unrecognized attribute 'targetFramework'. Note that attribute names are case-sensitive. (D:\lowSite4\web.config line 11)
12017정성태9/11/201921602오류 유형: 566. 비주얼 스튜디오 - Failed to register URL "http://localhost:6879/" for site "..." application "/". Error description: Access is denied. (0x80070005)
... 76  [77]  78  79  80  81  82  83  84  85  86  87  88  89  90  ...