Inter-process communication-Named Pipe and mail slot

Source: Internet
Author: User

 

Two Methods of inter-process communication are introduced: clipboard and anonymous pipeline. The two processes can communicate only between processes on the local host. While the anonymous pipeline also restricts the need for a parent-child relationship between two processes for communication. When developing applications that communicate with each other between different processes on the network, we can use the named pipe and mail slot. These two methods not only support local host communication but also internetprocess communication. The following two methods are described in detail:

1. Named Pipe

When the named pipe is used as a network communication solution, it actually establishes a Client/Server Communication System and reliably transmits data in it. The named pipeline is a mechanism designed around the Windows File System. It uses the "Naming pipeline File System excuse". Therefore, the client and server can use standard Win32 file system functions to send and receive data. When a named pipe is used for communication, the server is the only process that has the right to establish a named pipe and can receive client connection requests. The client can only establish a connection with an existing Named Pipe client. The named pipe provides two basic communication modes: byte mode and message mode. In the actual programming process, you can select different communication modes as needed. Follow these steps to use the Named Pipe for communication:

(1) server side:

(1) create a named pipe

Before using the Named Pipe for communication, you must first create a named pipe. The function to be called to create a named pipeline isCreateNamedPipe (),This function creates an instance named pipeline and returns the handle of the instance. The first parameter of this function saves the name of the created pipeline in the specified format. The second parameter of this function specifies the inbound mode, overlapping mode, read/write mode, and security attributes of the pipeline. In the following example, I use bidirectional inbound mode.(PIPE_ACCESS_DUPLEX)Both the client and server can read and write data from the pipeline. The overlapping mode can be overlapped.(FILE_FLAG_OVERLAPPED)After specifying the overlap mode, the thread that takes the time will immediately return and execute other operations, and the time-consuming thread will complete in the background. The fourth parameter of this function specifies the maximum number of instances that can be created for this pipeline. This parameter is specified because the example of a named pipe can only communicate with one client. If multiple clients need to communicate with the server through the named pipe, you need to create multiple instances of the named pipeline. The sample code for creating a named pipe is as follows:

/*************************************** ************
Create a named pipe
**************************************** ***************/
HPipe = CreateNamedPipe ("\\\\\ pipe \ MyPipe", PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
0, 1, 0, NULL );
If (INVALID_HANDLE_VALUE = hPipe)
{
MessageBox ("An error occurred while creating the named pipe! ");
HPipe = NULL;
// CloseHandle (hPipe );
Return;
}

(2) Wait for the arrival of client connection requests

After the named pipe is created, the server can wait for the client connection request. The function waiting for the client connection request to be called isConnectNamedPipe ()The second parameter of this function is a pointOVERLAPPEDStruct pointer, which contains information used for asynchronous I/O operations. The parameter we are interested in this struct is a handle pointing to the event object. We can use this event object to perform asynchronous I/O operations. So we need to callCreateEvent ()Create a manually reset event object. After waiting for the client connection request, we can callWaitForSingleObject ()The function sets the event object to a non-signal state for the next connection request. The implementation code is as follows:

/*************************************** ******************
Create an anonymous event object reset by the Creator
**************************************** *****************/
HANDLE hEvent;
HEvent = CreateEvent (NULL, TRUE, FALSE, NULL );
If (! HEvent)
{
MessageBox ("The Creator failed to reset the anonymous event object! ");
CloseHandle (hEvent );
HPipe = NULL;
Return;
}
/*************************************** ******************
Wait for the client connection request to arrive
**************************************** *****************/
OVERLAPPED olp;
ZeroMemory (& olp, sizeof (OVERLAPPED ));
Olp. hEvent = hEvent;
If (! ConnectNamedPipe (hPipe, & olp ))
{
If (ERROR_IO_PENDING! = GetLastError ())
{
MessageBox ("failed to wait for client connection request! ");
CloseHandle (hPipe );
CloseHandle (hEvent );
HPipe = NULL;

Return;
}
}
If (WAIT_FAILED = WaitForSingleObject (hEvent, INFINITE ))
{
MessageBox ("failed to wait for the object! ");
CloseHandle (hPipe );
CloseHandle (hEvent );
HPipe = NULL;
Return;
}
CloseHandle (hEvent );

(3) read and write operations to the MPs queue

Because the named pipeline is designed around the file system, we can use the standard Win32 file operation function to perform read and write operations. The sample code is as follows:

Void CNamedPipeSrvView: OnPipRead ()
{
// TODO: Add your command handler code here
Char buf [200];
DWORD dwRead;
If (! ReadFile (hPipe, buf, 200, & dwRead, NULL ))
{
MessageBox ("failed to read anonymous pipeline! ");
Return;
}
MessageBox (buf );
}


Void CNamedPipeSrvView: OnPipWrite ()
{
// TODO: Add your command handler code here
Char buf [] = "anonymous pipeline test program! ";
DWORD dwWrite;
If (! WriteFile (hPipe, buf, strlen (buf) + 1, & dwWrite, NULL ))
{
MessageBox ("failed to write anonymous pipeline! ");
Return;
}
}
(2) Client

The implementation of the named pipeline is relatively simple. The client first checks whether there is an available named pipeline instance. If yes, the client can open the pipeline to perform read and write operations.

(1) connect to the MPs queue instance and open the MPs queue

WaitNamedPipe ()A function can be used to connect to a named pipe instance. After the connection is successful, you can callCreateFile ()Function to open the pipeline. This function can specify the Pipeline Entry Mode and file attributes. The sample code is as follows:

**************************************** ******************
Determine whether an available named pipeline instance exists
**************************************** ********************/
If (! WaitNamedPipe ("\\\\\ pipe \\ MyPipe", NMPWAIT_WAIT_FOREVER ))
{
MessageBox ("there are no named pipeline instances available currently ");
Return;
}
/*************************************** *******************
Open named Pipeline
**************************************** ********************/
HPipe = CreateFile ("\\\\\ pipe \\ MyPipe", GENERIC_READ | GENERIC_WRITE,
0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL );
If (INVALID_HANDLE_VALUE = hPipe)
{
MessageBox ("failed to open MPs queue! ");
HPipe = NULL;
Return;
}

(2) read and write data to the MPs queue

Void CNamedPipeCltView: OnPipRead ()
{
// TODO: Add your command handler code here
Char buf [200];
DWORD dwRead;
If (! ReadFile (hPipe, buf, 200, & dwRead, NULL ))
{
MessageBox ("failed to read anonymous pipeline! ");
Return;
}
MessageBox (buf );
}


Void CNamedPipeCltView: OnPipWrite ()
{
// TODO: Add your command handler code here
Char buf [] = "Ride wind 736 blog Park http://www.cnblogs.com/chengfeng736 ";

DWORD dwWrite;
If (! WriteFile (hPipe, buf, strlen (buf) + 1, & dwWrite, NULL ))
{
MessageBox ("failed to write anonymous pipeline! ");
Return;
}
}

The running result is as follows:

In this way, a server and client program that communicates through a named pipeline are designed. The two processes can implement communication.

Ii. Mail Trough

The mail slot is a one-way communication method based on the broadcast mode. The server can only read data from the mail slot, the client can only write data to the mail slot, and the amount of information transmitted by the mail slot cannot be too large. The following describes the process of Process Communication Using the mail slot:

(1) servers

(1) create a tank

Adjustable for creating Oil TanksCreateMailslot ()Function implementation. The first parameter of the function specifies the name of the slot according to the specified format, and the third parameter specifies the read operation wait time. In the following example, I set the read operation to wait.(MAILSLOT_WAIT_FOREVER ),Only until the data is received. The sample code is as follows:

HANDLE hMailslot;
HMailslot = CreateMailslot ("\\\\\ mailslot \ MyMailslot", 0, MAILSLOT_WAIT_FOREVER, NULL );
If (INVALID_HANDLE_VALUE = hMailslot)
{
MessageBox ("An error occurred while creating the mailbox! ");
CloseHandle (hMailslot );
Return;
}

(2) read data

DWORD dwRead;
Char buf [200];
If (! ReadFile (hMailslot, buf, 200, & dwRead, NULL ))
{
MessageBox ("failed to read data! ");
CloseHandle (hMailslot );
Return;
}
MessageBox (buf );
CloseHandle (hMailslot );

(2) Client

(1) Open the Oil Tank

CreateFile ()Function can not only open files, pipelines, but also open the oil slot. The sample code is as follows:

HANDLE hMailslot;
HMailslot = CreateFile ("\\\\\. \ mailslot \ MyMailslot", GENERIC_WRITE, file_assist_read,
NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL );
If (INVALID_HANDLE_VALUE = hMailslot)
{
MessageBox ("failed to open the mailbox! ");
CloseHandle (hMailslot );
Return;
}

(2) Write Data

Char buf [] = "using the mail slot for inter-process communication \ r \ n take the wind 736 blog Park http://www.cnblogs.com/chengfeng736 ";

DWORD dwWrite;
If (! WriteFile (hMailslot, buf, strlen (buf) + 1, & dwWrite, 0 ))
{
MessageBox ("failed to write data! ");
CloseHandle (hMailslot );
Return;
}
CloseHandle (hMailslot );

The running result is as follows:

It is very easy to implement communication with tanks. The oil tank can only communicate in one direction. To achieve two-way communication, you can perform read/write operations on the client and server separately.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.