Software/Tools

[API] Process Communication[2]

charom 2007. 8. 5. 22:16

Creating Named Shared Memory

The first process calls the CreateFileMapping function to create a file mapping object and give it the name MyFileMappingObject. By using the PAGE_READWRITE flag, the processes will have read/write permission to the memory through any file views that are created.

Note that ErrorHandler is a placeholder for a user-defined function that displays an error message and exits the code.

 

 

#include <windows.h> HANDLE hFile, hMapFile; hFile = CreateFile( lpszName, // name of existing file GENERIC_READ | GENERIC_WRITE, // read/write access 0, // no sharing NULL, // default security OPEN_ALWAYS, // open existing or new FILE_ATTRIBUTE_NORMAL, // file attributes NULL); // no template if (hFile == INVALID_HANDLE_VALUE ) { ErrorHandler("Could not open file."); } hMapFile = CreateFileMapping(hFile, // current file handle NULL, // default security PAGE_READWRITE, // read/write permission 0, // max. object size 0, // size of hFile "MyFileMappingObject"); // name of mapping object if (hMapFile == NULL) { ErrorHandler("Could not create file mapping object."); }

The process then uses the file mapping object handle returned by CreateFileMapping in the call to MapViewOfFile to create a view of the file in the process's address space. The MapViewOfFile function returns a pointer to the file view.

 

LPVOID lpMapAddress; lpMapAddress = MapViewOfFile(hMapFile, // handle to mapping object FILE_MAP_ALL_ACCESS, // read/write permission 0, // max. object size 0, // size of hFile 0); // map entire file if (lpMapAddress == NULL) { ErrorHandler("Could not map view of file."); }

The second process calls the OpenFileMapping function with the name MyFileMappingObject to use the same file mapping object as the first process. Like the first process, the second process uses the MapViewOfFile function to obtain a pointer to the file view.

 

HANDLE hMapFile; LPVOID lpMapAddress; hMapFile = OpenFileMapping(FILE_MAP_ALL_ACCESS, // read/write permission FALSE, // Do not inherit the name "MyFileMappingObject"); // of the mapping object. if (hMapFile == NULL) { ErrorHandler("Could not open file mapping object."); } lpMapAddress = MapViewOfFile(hMapFile, // handle to mapping object FILE_MAP_ALL_ACCESS, // read/write permission 0, // max. object size 0, // size of hFile 0); // map entire file if (lpMapAddress == NULL) { ErrorHandler("Could not map view of file."); }

 

CreateFileMapping

 

The CreateFileMapping function creates or opens a named or unnamed file mapping object for the specified file.

 

HANDLE CreateFileMapping( HANDLE hFile,  LPSECURITY_ATTRIBUTES lpAttributes,  DWORD flProtect,  DWORD dwMaximumSizeHigh,  DWORD dwMaximumSizeLow,  LPCTSTR lpName ); 

Parameters

hFile
[in] Handle to the file from which to create a mapping object. The file must be opened with access rights compatible with the protection flags specified by the flProtect parameter. It is recommended, though not required, that files you intend to map be opened for exclusive access. For more information, see File Security and Access Rights.

If hFile is INVALID_HANDLE_VALUE, the calling process must also specify a mapping object size in the dwMaximumSizeHigh and dwMaximumSizeLow parameters. In this case, CreateFileMapping creates a file mapping object of the specified size backed by the operating-system paging file rather than by a named file in the file system. The file mapping object can be shared through duplication, through inheritance, or by name. The initial contents of the pages in the file mapping object are zero.

lpAttributes
[in] Pointer to a SECURITY_ATTRIBUTES structure that determines whether the returned handle can be inherited by child processes. If lpAttributes is NULL, the handle cannot be inherited.

The lpSecurityDescriptor member of the structure specifies a security descriptor for the new file mapping object. If lpAttributes is NULL, the file mapping object gets a default security descriptor. The ACLs in the default security descriptor for a file mapping object come from the primary or impersonation token of the creator. Note that doing this involves potential security risks. To avoid these risks, use a valid SECURITY_ATTRIBUTES structure.

flProtect
[in] Protection desired for the file view, when the file is mapped. This parameter can be one of the following values.
Value Meaning
PAGE_READONLY Gives read-only access to the committed region of pages. An attempt to write to or execute the committed region results in an access violation. The file specified by the hFile parameter must have been created with the GENERIC_READ access right.
PAGE_READWRITE Gives read/write access to the committed region of pages. The file specified by hFile must have been created with the GENERIC_READ and GENERIC_WRITE access rights.
PAGE_WRITECOPY Gives copy-on-write access to the committed region of pages. The files specified by the hFile parameter must have been created with the GENERIC_READ and GENERIC_WRITE access rights.

 

In addition, an application can specify certain section attributes by combining (using the bitwise OR operator) one or more of the following section attribute values with one of the preceding page protection values.

 

Value Meaning
SEC_COMMIT Allocates physical storage in memory or in the paging file on disk for all pages of a section. This is the default setting.
SEC_IMAGE The file specified for a section's file mapping is an executable image file. Because the mapping information and file protection are taken from the image file, no other attributes are valid with SEC_IMAGE.
Windows Me/98/95:  This flag is not supported.
SEC_NOCACHE All pages of a section are to be set as noncacheable. Applications should not use this flag except when explicitly required for a device. Using the interlocked functions with memory mapped by a SEC_NOCACHE section can result in a STATUS_ILLEGAL_INSTRUCTION exception. Note that SEC_NOCACHE requires either the SEC_RESERVE or SEC_COMMIT to also be set.
Windows Me/98/95:  This flag is not supported.
SEC_RESERVE Reserves all pages of a section without allocating physical storage. The reserved range of pages cannot be used by any other allocation operations until it is released. Reserved pages can be committed in subsequent calls to the VirtualAlloc function. This attribute is valid only if the hFile parameter is INVALID_HANDLE_VALUE; that is, a file mapping object backed by the operating system paging file.
dwMaximumSizeHigh
[in] High-order DWORD of the maximum size of the file mapping object.
dwMaximumSizeLow
[in] Low-order DWORD of the maximum size of the file mapping object. If this parameter and dwMaximumSizeHigh are zero, the maximum size of the file mapping object is equal to the current size of the file identified by hFile.

An attempt to map a file with a length of zero in this manner fails with an error code of ERROR_FILE_INVALID. Applications should test for files with a length of zero and reject such files.

lpName
[in] Pointer to a null-terminated string specifying the name of the mapping object.

If this parameter matches the name of an existing named mapping object, the function requests access to the mapping object with the protection specified by flProtect.

If this parameter is NULL, the mapping object is created without a name.

If lpName matches the name of an existing event, semaphore, mutex, waitable timer, or job object, the function fails and the GetLastError function returns ERROR_INVALID_HANDLE. This occurs because these objects share the same name space.

Terminal Services:  The name can have a "Global\" or "Local\" prefix to explicitly create the object in the global or session name space. The remainder of the name can contain any character except the backslash character (\). For more information, see Kernel Object Namespaces.
Windows XP Home Edition:  Fast user switching is implemented using Terminal Services sessions. The first user to log on uses session 0, the next user to log on uses session 1, and so on. Kernel object names must follow the guidelines outlined for Terminal Services so that applications can support multiple users.
Windows 2000:  If Terminal Services is not running, the "Global\" and "Local\" prefixes are ignored. The remainder of the name can contain any character except the backslash character.
Windows NT:  The name can contain any character except the backslash character.
Windows Me/98/95:  The name can contain any character except the backslash character. The empty string ("") is a valid object name.

Return Values

If the function succeeds, the return value is a handle to the file mapping object. If the object existed before the function call, the function returns a handle to the existing object (with its current size, not the specified size) and GetLastError returns ERROR_ALREADY_EXISTS.

If the function fails, the return value is NULL. To get extended error information, call GetLastError.

Remarks

After a file mapping object has been created, the size of the file must not exceed the size of the file mapping object; if it does, not all of the file's contents will be available for sharing.

If an application specifies a size for the file mapping object that is larger than the size of the actual named file on disk, the file on disk is grown to match the specified size of the file mapping object. If the file cannot be grown, this results in a failure to create the file mapping object. GetLastError will return ERROR_DISK_FULL.

The handle that CreateFileMapping returns has full access to the new file mapping object. It can be used with any function that requires a handle to a file mapping object. File mapping objects can be shared either through process creation, through handle duplication, or by name. For information on duplicating handles, see DuplicateHandle. For information on opening a file mapping object by name, see OpenFileMapping.

Windows Me/98/95:  File handles that have been used to create file mapping objects must not be used in subsequent calls to file I/O functions, such as ReadFile and WriteFile. In general, if a file handle has been used in a successful call to the CreateFileMapping function, do not use that handle unless you first close the corresponding file mapping object.

Creating a file mapping object creates the potential for mapping a view of the file but does not map the view. The MapViewOfFile and MapViewOfFileEx functions map a view of a file into a process's address space.

With one important exception, file views derived from a single file mapping object are coherent, or identical, at a given time. If multiple processes have handles of the same file mapping object, they see a coherent view of the data when they map a view of the file.

The exception has to do with remote files. Although CreateFileMapping works with remote files, it does not keep them coherent. For example, if two computers both map a file as writable, and both change the same page, each computer will only see its own writes to the page. When the data gets updated on the disk, it is not merged.

A mapped file and a file accessed by means of the input and output (I/O) functions ( ReadFile and WriteFile) are not necessarily coherent.

To fully close a file mapping object, an application must unmap all mapped views of the file mapping object by calling UnmapViewOfFile, and close the file mapping object handle by calling CloseHandle. The order in which these functions are called does not matter. The call to UnmapViewOfFile is necessary because mapped views of a file mapping object maintain internal open handles to the object, and a file mapping object will not close until all open handles to it are closed.

 

Terminal Services sessions can use shared memory blocks to transfer data between processes spawned by those sessions. If you do this, keep in mind that shared memory cannot be used in situations where both of the following conditions exist:

 

  • All of the processes using the shared memory block were not spawned by one session.
  • All of the sessions share the same user logon credential.

To guard against an access violation, use structured exception handling to protect any code that writes to or reads from a memory mapped view. For more information, see Reading and Writing From a File View.

 

 

Windows Me/98/95:  CreateFileMappingW is supported by the Microsoft Layer for Unicode. To use this, you must add certain files to your application, as outlined in Microsoft Layer for Unicode on Windows 95/98/Me Systems.

 

Example Code

To implement a mapping-object creation function that fails if the object already exists, an application can use the following code.

hMap = CreateFileMapping(...); if (hMap != NULL && GetLastError() == ERROR_ALREADY_EXISTS) { CloseHandle(hMap); hMap = NULL; } return hMap;

Example Code

For an example, see Creating Named Shared Memory.

Requirements

Client: Requires Windows XP, Windows 2000 Professional, Windows NT Workstation, Windows Me, Windows 98, or Windows 95.
Server: Requires Windows Server 2003, Windows 2000 Server, or Windows NT Server.
Unicode: Implemented as Unicode and ANSI versions. Note that Unicode support on Windows Me/98/95 requires Microsoft Layer for Unicode.
Header: Declared in Winbase.h; include Windows.h.
Library: Use Kernel32.lib.
 

See Also

File Management Functions, CloseHandle, DuplicateHandle, MapViewOfFile, MapViewOfFileEx, OpenFileMapping, ReadFile, SECURITY_ATTRIBUTES, UnmapViewOfFile, VirtualAlloc, WriteFile