The Labs \ Source Viewer \ SSCLI \ Microsoft.Win32.SafeHandles \ SafeProcessHandle

  1. // ==++==
  2. //
  3. //
  4. // Copyright (c) 2006 Microsoft Corporation. All rights reserved.
  5. //
  6. // The use and distribution terms for this software are contained in the file
  7. // named license.txt, which can be found in the root of this distribution.
  8. // By using this software in any fashion, you are agreeing to be bound by the
  9. // terms of this license.
  10. //
  11. // You must not remove this notice, or any other, from this software.
  12. //
  13. //
  14. // ==--==
  15. /*============================================================
  16. **
  17. ** Class:  SafeProcessHandle
  18. **
  19. ** A wrapper for a process handle
  20. **
  21. **
  22. ===========================================================*/
  23. using System;
  24. using System.Security;
  25. using System.Diagnostics;
  26. using System.Security.Permissions;
  27. using System.Runtime.InteropServices;
  28. using System.Runtime.CompilerServices;
  29. using Microsoft.Win32;
  30. using Microsoft.Win32.SafeHandles;
  31. using System.Runtime.ConstrainedExecution;
  32. namespace Microsoft.Win32.SafeHandles
  33. {
  34.     [HostProtectionAttribute(MayLeakOnAbort = true)]
  35.     [SuppressUnmanagedCodeSecurityAttribute()]
  36.     internal sealed class SafeProcessHandle : SafeHandleZeroOrMinusOneIsInvalid
  37.     {
  38.         static internal SafeProcessHandle InvalidHandle = new SafeProcessHandle(IntPtr.Zero);
  39.        
  40.         // Note that OpenProcess returns 0 on failure
  41.        
  42.         internal SafeProcessHandle() : base(true)
  43.         {
  44.         }
  45.        
  46.         [SecurityPermission(SecurityAction.LinkDemand, UnmanagedCode = true)]
  47.         internal SafeProcessHandle(IntPtr handle) : base(true)
  48.         {
  49.             SetHandle(handle);
  50.         }
  51.        
  52.         // Not currently called
  53.         //[SecurityPermission(SecurityAction.LinkDemand, UnmanagedCode=true)]
  54.         //internal SafeProcessHandle(IntPtr existingHandle, bool ownsHandle) : base(ownsHandle) {
  55.         // SetHandle(existingHandle);
  56.         //}
  57.        
  58.         [DllImport(ExternDll.Kernel32, CharSet = System.Runtime.InteropServices.CharSet.Auto, SetLastError = true)]
  59.         static internal extern SafeProcessHandle OpenProcess(int access, bool inherit, int processId);
  60.        
  61.        
  62.         internal void InitialSetHandle(IntPtr h)
  63.         {
  64.             Debug.Assert(base.IsInvalid, "Safe handle should only be set once");
  65.             base.handle = h;
  66.         }
  67.        
  68.         protected override bool ReleaseHandle()
  69.         {
  70.             return SafeNativeMethods.CloseHandle(handle);
  71.         }
  72.        
  73.     }
  74. }

Developer Fusion