PageRenderTime 48ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 0ms

/Visual Studio 2008/CSFileMappingClient/Program.cs

#
C# | 276 lines | 225 code | 3 blank | 48 comment | 0 complexity | 8796c431f9d0f5e8b0bfbf3b885a6d97 MD5 | raw file
  1. /******************************** Module Header ********************************\
  2. * Module Name: Program.cs
  3. * Project: CSFileMappingClient
  4. * Copyright (c) Microsoft Corporation.
  5. *
  6. * File mapping is a mechanism for one-way or duplex inter-process communication
  7. * among two or more processes in the local machine. To share a file or memory,
  8. * all of the processes must use the name or the handle of the same file mapping
  9. * object.
  10. *
  11. * To share a file, the first process creates or opens a file by using the
  12. * CreateFile function. Next, it creates a file mapping object by using the
  13. * CreateFileMapping function, specifying the file handle and a name for the
  14. * file mapping object. The names of event, semaphore, mutex, waitable timer,
  15. * job, and file mapping objects share the same name space. Therefore, the
  16. * CreateFileMapping and OpenFileMapping functions fail if they specify a name
  17. * that is in use by an object of another type.
  18. *
  19. * To share memory that is not associated with a file, a process must use the
  20. * CreateFileMapping function and specify INVALID_HANDLE_VALUE as the hFile
  21. * parameter instead of an existing file handle. The corresponding file mapping
  22. * object accesses memory backed by the system paging file. You must specify a
  23. * size greater than zero when you use an hFile of INVALID_HANDLE_VALUE in a call
  24. * to CreateFileMapping.
  25. *
  26. * Processes that share files or memory must create file views by using the
  27. * MapViewOfFile or MapViewOfFileEx function. They must coordinate their access
  28. * using semaphores, mutexes, events, or some other mutual exclusion technique.
  29. *
  30. * The VC# code sample demonstrates opening a file mapping object named
  31. * "Local\SampleMap" and reading the string written to the file mapping by other
  32. * process. Because the Base Class Library of .NET Framework 2/3/3.5 does not have
  33. * any public classes to operate on file mapping objects, you have to P/Invoke the
  34. * Windows APIs as shown in this code sample.
  35. *
  36. * This source is subject to the Microsoft Public License.
  37. * See http://www.microsoft.com/opensource/licenses.mspx#Ms-PL.
  38. * All other rights reserved.
  39. *
  40. * THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND,
  41. * EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED
  42. * WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE.
  43. \*******************************************************************************/
  44. #region Using directives
  45. using System;
  46. using System.Runtime.InteropServices;
  47. using System.Security;
  48. using System.Security.Permissions;
  49. using Microsoft.Win32.SafeHandles;
  50. using System.Runtime.ConstrainedExecution;
  51. using System.ComponentModel;
  52. #endregion
  53. namespace CSFileMappingClient
  54. {
  55. class Program
  56. {
  57. // In terminal services: The name can have a "Global\" or "Local\"
  58. // prefix to explicitly create the object in the global or session
  59. // namespace. The remainder of the name can contain any character except
  60. // the backslash character (\). For more information, see:
  61. // http://msdn.microsoft.com/en-us/library/aa366537.aspx
  62. internal const string MapPrefix = "Local\\";
  63. internal const string MapName = "SampleMap";
  64. internal const string FullMapName = MapPrefix + MapName;
  65. // File offset where the view is to begin.
  66. internal const uint ViewOffset = 0;
  67. // The number of bytes of a file mapping to map to the view. All bytes of
  68. // the view must be within the maximum size of the file mapping object.
  69. // If VIEW_SIZE is 0, the mapping extends from the offset (VIEW_OFFSET)
  70. // to the end of the file mapping.
  71. internal const uint ViewSize = 1024;
  72. static void Main(string[] args)
  73. {
  74. SafeFileMappingHandle hMapFile = null;
  75. IntPtr pView = IntPtr.Zero;
  76. try
  77. {
  78. // Try to open the named file mapping.
  79. hMapFile = NativeMethod.OpenFileMapping(
  80. FileMapAccess.FILE_MAP_READ, // Read access
  81. false, // Do not inherit the name
  82. FullMapName // File mapping name
  83. );
  84. if (hMapFile.IsInvalid)
  85. {
  86. throw new Win32Exception();
  87. }
  88. Console.WriteLine("The file mapping ({0}) is opened", FullMapName);
  89. // Map a view of the file mapping into the address space of the
  90. // current process.
  91. pView = NativeMethod.MapViewOfFile(
  92. hMapFile, // Handle of the map object
  93. FileMapAccess.FILE_MAP_READ, // Read access
  94. 0, // High-order DWORD of file offset
  95. ViewOffset, // Low-order DWORD of file offset
  96. ViewSize // Byte# to map to view
  97. );
  98. if (pView == IntPtr.Zero)
  99. {
  100. throw new Win32Exception();
  101. }
  102. Console.WriteLine("The file view is mapped");
  103. // Read and display the content in the view.
  104. string message = Marshal.PtrToStringUni(pView);
  105. Console.WriteLine("Read from the file mapping:\n\"{0}\"", message);
  106. // Wait to clean up resources and stop the process.
  107. Console.Write("Press ENTER to clean up resources and quit");
  108. Console.ReadLine();
  109. }
  110. catch (Exception ex)
  111. {
  112. Console.WriteLine("The process throws the error: {0}", ex.Message);
  113. }
  114. finally
  115. {
  116. if (hMapFile != null)
  117. {
  118. if (pView != IntPtr.Zero)
  119. {
  120. // Unmap the file view.
  121. NativeMethod.UnmapViewOfFile(pView);
  122. pView = IntPtr.Zero;
  123. }
  124. // Close the file mapping object.
  125. hMapFile.Close();
  126. hMapFile = null;
  127. }
  128. }
  129. }
  130. #region Native API Signatures and Types
  131. /// <summary>
  132. /// Access rights for file mapping objects
  133. /// http://msdn.microsoft.com/en-us/library/aa366559.aspx
  134. /// </summary>
  135. [Flags]
  136. public enum FileMapAccess
  137. {
  138. FILE_MAP_COPY = 0x0001,
  139. FILE_MAP_WRITE = 0x0002,
  140. FILE_MAP_READ = 0x0004,
  141. FILE_MAP_ALL_ACCESS = 0x000F001F
  142. }
  143. /// <summary>
  144. /// Represents a wrapper class for a file mapping handle.
  145. /// </summary>
  146. [SuppressUnmanagedCodeSecurity,
  147. HostProtection(SecurityAction.LinkDemand, MayLeakOnAbort = true)]
  148. internal sealed class SafeFileMappingHandle : SafeHandleZeroOrMinusOneIsInvalid
  149. {
  150. [SecurityPermission(SecurityAction.LinkDemand, UnmanagedCode = true)]
  151. private SafeFileMappingHandle()
  152. : base(true)
  153. {
  154. }
  155. [SecurityPermission(SecurityAction.LinkDemand, UnmanagedCode = true)]
  156. public SafeFileMappingHandle(IntPtr handle, bool ownsHandle)
  157. : base(ownsHandle)
  158. {
  159. base.SetHandle(handle);
  160. }
  161. [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success),
  162. DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
  163. [return: MarshalAs(UnmanagedType.Bool)]
  164. private static extern bool CloseHandle(IntPtr handle);
  165. protected override bool ReleaseHandle()
  166. {
  167. return CloseHandle(base.handle);
  168. }
  169. }
  170. /// <summary>
  171. /// The class exposes Windows APIs used in this code sample.
  172. /// </summary>
  173. [SuppressUnmanagedCodeSecurity]
  174. internal class NativeMethod
  175. {
  176. /// <summary>
  177. /// Opens a named file mapping object.
  178. /// </summary>
  179. /// <param name="dwDesiredAccess">
  180. /// The access to the file mapping object. This access is checked against
  181. /// any security descriptor on the target file mapping object.
  182. /// </param>
  183. /// <param name="bInheritHandle">
  184. /// If this parameter is TRUE, a process created by the CreateProcess
  185. /// function can inherit the handle; otherwise, the handle cannot be
  186. /// inherited.
  187. /// </param>
  188. /// <param name="lpName">
  189. /// The name of the file mapping object to be opened.
  190. /// </param>
  191. /// <returns>
  192. /// If the function succeeds, the return value is an open handle to the
  193. /// specified file mapping object.
  194. /// </returns>
  195. [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
  196. public static extern SafeFileMappingHandle OpenFileMapping(
  197. FileMapAccess dwDesiredAccess, bool bInheritHandle, string lpName);
  198. /// <summary>
  199. /// Maps a view of a file mapping into the address space of a calling
  200. /// process.
  201. /// </summary>
  202. /// <param name="hFileMappingObject">
  203. /// A handle to a file mapping object. The CreateFileMapping and
  204. /// OpenFileMapping functions return this handle.
  205. /// </param>
  206. /// <param name="dwDesiredAccess">
  207. /// The type of access to a file mapping object, which determines the
  208. /// protection of the pages.
  209. /// </param>
  210. /// <param name="dwFileOffsetHigh">
  211. /// A high-order DWORD of the file offset where the view begins.
  212. /// </param>
  213. /// <param name="dwFileOffsetLow">
  214. /// A low-order DWORD of the file offset where the view is to begin.
  215. /// </param>
  216. /// <param name="dwNumberOfBytesToMap">
  217. /// The number of bytes of a file mapping to map to the view. All bytes
  218. /// must be within the maximum size specified by CreateFileMapping.
  219. /// </param>
  220. /// <returns>
  221. /// If the function succeeds, the return value is the starting address
  222. /// of the mapped view.
  223. /// </returns>
  224. [DllImport("Kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
  225. public static extern IntPtr MapViewOfFile(
  226. SafeFileMappingHandle hFileMappingObject,
  227. FileMapAccess dwDesiredAccess,
  228. uint dwFileOffsetHigh,
  229. uint dwFileOffsetLow,
  230. uint dwNumberOfBytesToMap);
  231. /// <summary>
  232. /// Unmaps a mapped view of a file from the calling process's address
  233. /// space.
  234. /// </summary>
  235. /// <param name="lpBaseAddress">
  236. /// A pointer to the base address of the mapped view of a file that
  237. /// is to be unmapped.
  238. /// </param>
  239. /// <returns></returns>
  240. [DllImport("Kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
  241. [return: MarshalAs(UnmanagedType.Bool)]
  242. public static extern bool UnmapViewOfFile(IntPtr lpBaseAddress);
  243. }
  244. #endregion
  245. }
  246. }