Inter-Process Communication (IPC) is a set of techniques for the exchange of data among multiple threads in one or more processes. Processes may be running on one or more computers connected by a network. IPC techniques include Named Pipes, File Mapping, Mailslot, Remote Procedure Calls (RPC), etc.
In All-In-One Code Framework, we have already implemented samples (C++ and C#) for Named Pipes, File Mapping, Mail Slot, and Remoting. We are going to add more techniques like: Clickbord, Winsock, etc. You can download the latest code from http://cfx.codeplex.com/.
All-In-One Code Framework (short as AIO) delineates the framework and skeleton of most Microsoft development techniques (e.g., COM, Data Access, IPC) using typical sample codes in different programming languages (e.g., Visual C#, VB.NET, Visual C++).
Using the Code
Find samples by following the steps below:
- Download the zip file and unzip it.
- Open the folder [Visual Studio 2008].
- Open the solution file IPC.sln. You must pre-install Visual Studio 2008 on the machine.
- In the Solution Explorer, open the [Process] \ [IPC and RPC] folder.
Samples Structure and Relationship
Named pipes is a mechanism for one-way or bi-directional inter-process communication between a pipe server and one or more pipe clients in the local machine or across computers in an intranet:
Client (GENERIC_WRITE) ---> Server (GENERIC_READ)
Client (GENERIC_READ) <--- Server (GENERIC_WRITE)
Client (GENERIC_READ or GENERIC_WRITE, or both)
<--> Server (GENERIC_READ and GENERIC_WRITE)
This sample demonstrates a named pipe server, \\.\pipe\HelloWorld, that supports
PIPE_ACCESS_DUPLEX. It first creates such a named pipe, then it listens to the client's connection. When a client is connected, the server attempts to read the client's requests from the pipe and writes a response.
A named pipe client attempts to connect to the pipe server, \\.\pipe\HelloWorld, with the
GENERIC_WRITE permissions. The client writes a message to the pipe server and receives its response.
- Create a named pipe. (
- Wait for the client to connect. (
- Read client requests from the pipe and write the response. (
- Disconnect the pipe, and close the handle. (
- Try to open a named pipe. (
- Set the read mode and the blocking mode of the specified named pipe. (
- Send a message to the pipe server and receive its response. (
- Close the pipe. (
Code - CreateNamedPipe (C++)
HANDLE hPipe = CreateNamedPipe(
strPipeName, PIPE_ACCESS_DUPLEX, PIPE_TYPE_MESSAGE | PIPE_READMODE_MESSAGE | PIPE_WAIT, PIPE_UNLIMITED_INSTANCES,
BUFFER_SIZE, BUFFER_SIZE, NMPWAIT_USE_DEFAULT_WAIT, &sa )
For more code samples, please download AIO source code.
Security Attribute for Named Pipes
NULL, the named pipe gets a default security descriptor and the handle cannot be inherited. The ACLs in the default security descriptor for a named pipe grants full control to the LocalSystem account, administrators, and the creator owner. They also grant read access to members of the Everyone group and the anonymous account. In other words, with
NULL as the security attribute, the named pipe cannot be connected with WRITE permission across the network, or from a local client running as a lower integrity level. Here, we fill the security attributes to grant EVERYONE all access (not just the connect access) to the server. This solves the cross-network and cross-IL issues, but it creates a security hole right there: the clients have WRITE_OWNER access and then the server just loses the control of the pipe object.
Code - Security Attributes (C++)
sa.lpSecurityDescriptor = (PSECURITY_DESCRIPTOR)malloc(SECURITY_DESCRIPTOR_MIN_LENGTH);
SetSecurityDescriptorDacl(sa.lpSecurityDescriptor, TRUE, NULL, FALSE);
sa.nLength = sizeof(sa);
sa.bInheritHandle = TRUE;
.NET Named Pipe
.NET supports named pipes in two ways:
- P/Invoke the native APIs.
By P/Invoke-ing the native APIs from .NET, we can mimic the code logic in
CppNamedPipeServer to create the named pipe server, \\.\pipe\HelloWorld, that supports
PInvokeNativePipeServer first creates such a named pipe, then it listens to the client's connection. When a client is connected, the server attempts to read the client's requests from the pipe and write a response.
In .NET Framework 3.5, the namespace
System.IO.Pipes and a set of classes (e.g.,
NamedPipeServerStream) are added to the .NET BCL. These classes make the programming of named pipes in .NET much easier and safer than P/Invoke-ing the native APIs directly.
BCLSystemIOPipeServer first creates such a named pipe, then it listens to the client's connection. When a client is connected, the server attempts to read the client's requests from the pipe and write a response.
Code - Create Named Pipe (C#)
PipeSecurity pipeSa = new PipeSecurity();
pipeServer = new NamedPipeServerStream(
strPipeName, PipeDirection.InOut, NamedPipeServerStream.MaxAllowedServerInstances,
PipeTransmissionMode.Message, PipeOptions.None, BUFFER_SIZE, BUFFER_SIZE, pipeSa, HandleInheritability.None );
File mapping is a mechanism for one-way or bi-directional inter-process communication among two or more processes in the local machine. To share a file or memory, all of the processes must use the name or the handle of the same file mapping object.
To share a file, the first process creates or opens a file by using the
CreateFile function. Next, it creates a file mapping object by using the
CreateFileMapping function, specifying the file handle and a name for the file mapping object. The names of events, semaphores, mutexes, waitable timers, jobs, and file mapping objects share the same namespace. Therefore, the
OpenFileMapping functions fail if they specify a name that is in use by an object of another type.
To share memory that is not associated with a file, a process must use the
CreateFileMapping function and specify
INVALID_HANDLE_VALUE as the
hFile parameter instead of an existing file handle. The corresponding file mapping object accesses memory backed by the system paging file. You must specify a size greater than zero when you specify an
INVALID_HANDLE_VALUE in a call to
Processes that share files or memory must create file views by using the
MapViewOfFileEx functions. They must coordinate their access using semaphores, mutexes, events, or some other mutual exclusion techniques.
This example demonstrates a named shared memory server, Local\HelloWorld, that creates the file mapping object with
INVALID_HANDLE_VALUE. By using the
PAGE_READWRITE flag, the process has read/write permission to the memory through any file view that is created.
The named shared memory client, Local\HelloWorld, can access the string written to the shared memory by the first process. The console displays the message "Message from the first process" that is read from the file mapping created by the first process.
- Create a file mapping. (
- Map the view of the file mapping into the address space of the current process. (
- Write message to the file view. (
- Unmap the file view and close the file mapping objects. (
- Try to open a named file mapping. (
- Maps the view of the file mapping into the address space of the current process. (
- Read message from the view of the shared memory.
- Unmap the file view and close the file mapping objects. (
Code - CreateFileMapping (C++)
TCHAR szMapFileName = _T("Local\\HelloWorld");
HANDLE hMapFile = CreateFileMapping(
NULL, PAGE_READWRITE, 0, BUFFER_SIZE, szMapFileName );
.NET only supports P/Invoke native APIs currently. By P/Invoke, .NET can simulate similar behaviors as native code.
Sample Code 4 (C# - P/Invoke)
[DllImport("Kernel32.dll", SetLastError = true)]
public static extern IntPtr CreateFileMapping(
IntPtr hFile, IntPtr lpAttributes, FileProtection flProtect, uint dwMaximumSizeHigh, uint dwMaximumSizeLow, string lpName );
Mailslot is a mechanism for one-way inter-process communication in the local machine or across computers in the intranet. Any client can store messages in a mailslot. The creator of the slot, i.e., the server, retrieves the messages that are stored there:
Client (GENERIC_WRITE) ---> Server (GENERIC_READ)
This sample demonstrates a mailslot server, \\.\mailslot\HelloWorld. It first creates such a mailslot, then it reads the new messages in the slot every five seconds. Then, a mailslot client connects and writes to the mailslot \\.\mailslot\HelloWorld.
- Create a mailslot. (
- Check messages in the mailslot. (
- Check for the number of messages in the mailslot. (
- Retrieve the messages one by one from the mailslot. While reading, update the number of messages that are left in the mailslot. (
- Close the handle of the mailslot instance. (
- Open the mailslot. (
- Write messages to the mailslot. (
- Close the slot. (
Code - GetMailslotInfo (C++)
bResult = GetMailslotInfo(
hMailslot, NULL, &cbMessageBytes, &cMessages, NULL);
Code - CreateMailslot (C# - P/Invoke)
[DllImport("kernel32.dll", SetLastError = true)]
public static extern IntPtr CreateMailslot(
string lpName, uint nMaxMessageSize, int lReadTimeout, IntPtr lpSecurityAttributes );
.NET Remoting is a mechanism for one-way inter-process communication and RPC between .NET applications in the local machine or across computers in the intranet and internet.
.NET Remoting allows an application to make a remotable object available across remoting boundaries, which includes different appdomains, processes, or even different computers connected by a network. .NET Remoting makes a reference of a remotable object available to a client application, which then instantiates and uses a remotable object as if it were a local object. However, the actual code execution happens at the server-side. All requests to the remotable object are proxied by the .NET Remoting runtime over Channel objects that encapsulate the actual transport mode, including TCP streams, HTTP streams, and named pipes. As a result, by instantiating proper Channel objects, a .NET Remoting application can be made to support different communication protocols without recompiling the application. The runtime itself manages the act of serialization and marshalling of objects across the client and server appdomains.
Code - Create and Register a Channel (C#)
IDictionary props = new Hashtable();
props["port"] = 6100; props["typeFilterLevel"] = TypeFilterLevel.Full;
BinaryClientFormatterSinkProvider clientProvider = null;
BinaryServerFormatterSinkProvider serverProvider =
serverProvider.TypeFilterLevel = TypeFilterLevel.Full;
TcpChannel tcpChannel = new TcpChannel(props, clientProvider, serverProvider);
Code - Register Remotable Types (VB.NET)
RemotingConfiguration.ApplicationName = "RemotingService"
Points of Interest
In the pilot phase of the AIO project, we focus on five techniques: COM, Library, IPC, Office, and Data Access. There has been 42 code examples in the project. The collection currently grows at a rate of seven examples per week.
This article was created on 3/12/2009.