PageRenderTime 27ms CodeModel.GetById 12ms app.highlight 9ms RepoModel.GetById 1ms 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
 45#region Using directives
 46using System;
 47using System.Runtime.InteropServices;
 48using System.Security;
 49using System.Security.Permissions;
 50using Microsoft.Win32.SafeHandles;
 51using System.Runtime.ConstrainedExecution;
 52using System.ComponentModel;
 53#endregion
 54
 55
 56namespace CSFileMappingClient
 57{
 58    class Program
 59    {
 60        // In terminal services: The name can have a "Global\" or "Local\" 
 61        // prefix to explicitly create the object in the global or session 
 62        // namespace. The remainder of the name can contain any character except
 63        // the backslash character (\). For more information, see: 
 64        // http://msdn.microsoft.com/en-us/library/aa366537.aspx
 65        internal const string MapPrefix = "Local\\";
 66        internal const string MapName = "SampleMap";
 67        internal const string FullMapName = MapPrefix + MapName;
 68
 69        // File offset where the view is to begin.
 70        internal const uint ViewOffset = 0;
 71
 72        // The number of bytes of a file mapping to map to the view. All bytes of 
 73        // the view must be within the maximum size of the file mapping object. 
 74        // If VIEW_SIZE is 0, the mapping extends from the offset (VIEW_OFFSET) 
 75        // to the end of the file mapping.
 76        internal const uint ViewSize = 1024;
 77
 78
 79        static void Main(string[] args)
 80        {
 81            SafeFileMappingHandle hMapFile = null;
 82            IntPtr pView = IntPtr.Zero;
 83
 84            try
 85            {
 86                // Try to open the named file mapping.
 87                hMapFile = NativeMethod.OpenFileMapping(
 88                    FileMapAccess.FILE_MAP_READ,    // Read access
 89                    false,                          // Do not inherit the name
 90                    FullMapName                     // File mapping name
 91                    );
 92
 93                if (hMapFile.IsInvalid)
 94                {
 95                    throw new Win32Exception();
 96                }
 97
 98                Console.WriteLine("The file mapping ({0}) is opened", FullMapName);
 99
100                // Map a view of the file mapping into the address space of the 
101                // current process.
102                pView = NativeMethod.MapViewOfFile(
103                    hMapFile,                       // Handle of the map object
104                    FileMapAccess.FILE_MAP_READ,    // Read access
105                    0,                              // High-order DWORD of file offset 
106                    ViewOffset,                     // Low-order DWORD of file offset
107                    ViewSize                        // Byte# to map to view
108                    );
109
110                if (pView == IntPtr.Zero)
111                {
112                    throw new Win32Exception();
113                }
114
115                Console.WriteLine("The file view is mapped");
116
117                // Read and display the content in the view.
118                string message = Marshal.PtrToStringUni(pView);
119                Console.WriteLine("Read from the file mapping:\n\"{0}\"", message);
120
121                // Wait to clean up resources and stop the process.
122                Console.Write("Press ENTER to clean up resources and quit");
123                Console.ReadLine();
124            }
125            catch (Exception ex)
126            {
127                Console.WriteLine("The process throws the error: {0}", ex.Message);
128            }
129            finally
130            {
131                if (hMapFile != null)
132                {
133                    if (pView != IntPtr.Zero)
134                    {
135                        // Unmap the file view.
136                        NativeMethod.UnmapViewOfFile(pView);
137                        pView = IntPtr.Zero;
138                    }
139                    // Close the file mapping object.
140                    hMapFile.Close();
141                    hMapFile = null;
142                }
143            }
144        }
145
146
147        #region Native API Signatures and Types
148
149        /// <summary>
150        /// Access rights for file mapping objects
151        /// http://msdn.microsoft.com/en-us/library/aa366559.aspx
152        /// </summary>
153        [Flags]
154        public enum FileMapAccess
155        {
156            FILE_MAP_COPY = 0x0001,
157            FILE_MAP_WRITE = 0x0002,
158            FILE_MAP_READ = 0x0004,
159            FILE_MAP_ALL_ACCESS = 0x000F001F
160        }
161
162
163        /// <summary>
164        /// Represents a wrapper class for a file mapping handle. 
165        /// </summary>
166        [SuppressUnmanagedCodeSecurity,
167        HostProtection(SecurityAction.LinkDemand, MayLeakOnAbort = true)]
168        internal sealed class SafeFileMappingHandle : SafeHandleZeroOrMinusOneIsInvalid
169        {
170            [SecurityPermission(SecurityAction.LinkDemand, UnmanagedCode = true)]
171            private SafeFileMappingHandle()
172                : base(true)
173            {
174            }
175
176            [SecurityPermission(SecurityAction.LinkDemand, UnmanagedCode = true)]
177            public SafeFileMappingHandle(IntPtr handle, bool ownsHandle)
178                : base(ownsHandle)
179            {
180                base.SetHandle(handle);
181            }
182
183            [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success),
184            DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
185            [return: MarshalAs(UnmanagedType.Bool)]
186            private static extern bool CloseHandle(IntPtr handle);
187
188            protected override bool ReleaseHandle()
189            {
190                return CloseHandle(base.handle);
191            }
192        }
193
194
195        /// <summary>
196        /// The class exposes Windows APIs used in this code sample.
197        /// </summary>
198        [SuppressUnmanagedCodeSecurity]
199        internal class NativeMethod
200        {
201            /// <summary>
202            /// Opens a named file mapping object.
203            /// </summary>
204            /// <param name="dwDesiredAccess">
205            /// The access to the file mapping object. This access is checked against 
206            /// any security descriptor on the target file mapping object.
207            /// </param>
208            /// <param name="bInheritHandle">
209            /// If this parameter is TRUE, a process created by the CreateProcess 
210            /// function can inherit the handle; otherwise, the handle cannot be 
211            /// inherited.
212            /// </param>
213            /// <param name="lpName">
214            /// The name of the file mapping object to be opened.
215            /// </param>
216            /// <returns>
217            /// If the function succeeds, the return value is an open handle to the 
218            /// specified file mapping object.
219            /// </returns>
220            [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
221            public static extern SafeFileMappingHandle OpenFileMapping(
222                FileMapAccess dwDesiredAccess, bool bInheritHandle, string lpName);
223
224
225            /// <summary>
226            /// Maps a view of a file mapping into the address space of a calling
227            /// process.
228            /// </summary>
229            /// <param name="hFileMappingObject">
230            /// A handle to a file mapping object. The CreateFileMapping and 
231            /// OpenFileMapping functions return this handle.
232            /// </param>
233            /// <param name="dwDesiredAccess">
234            /// The type of access to a file mapping object, which determines the 
235            /// protection of the pages.
236            /// </param>
237            /// <param name="dwFileOffsetHigh">
238            /// A high-order DWORD of the file offset where the view begins.
239            /// </param>
240            /// <param name="dwFileOffsetLow">
241            /// A low-order DWORD of the file offset where the view is to begin.
242            /// </param>
243            /// <param name="dwNumberOfBytesToMap">
244            /// The number of bytes of a file mapping to map to the view. All bytes 
245            /// must be within the maximum size specified by CreateFileMapping.
246            /// </param>
247            /// <returns>
248            /// If the function succeeds, the return value is the starting address 
249            /// of the mapped view.
250            /// </returns>
251            [DllImport("Kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
252            public static extern IntPtr MapViewOfFile(
253                SafeFileMappingHandle hFileMappingObject,
254                FileMapAccess dwDesiredAccess,
255                uint dwFileOffsetHigh,
256                uint dwFileOffsetLow,
257                uint dwNumberOfBytesToMap);
258
259
260            /// <summary>
261            /// Unmaps a mapped view of a file from the calling process's address 
262            /// space.
263            /// </summary>
264            /// <param name="lpBaseAddress">
265            /// A pointer to the base address of the mapped view of a file that 
266            /// is to be unmapped.
267            /// </param>
268            /// <returns></returns>
269            [DllImport("Kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
270            [return: MarshalAs(UnmanagedType.Bool)]
271            public static extern bool UnmapViewOfFile(IntPtr lpBaseAddress);
272        }
273
274        #endregion
275    }
276}