[Zz] Principle and Implementation of named pipeline programming under VC ++

Source: Internet
Author: User
Tags readfile
Pipeline (PIPE) is actually a shared memory used for inter-process communication. The process that creates the pipeline is called the pipeline server, and the process that connects to a pipeline is the pipeline client. A named pipe (Named Pipes) is a one-way or two-way communication between a pipe server and one or more pipe clients. All instances of a named MPs queue share the same MPs queue name, but each instance has an independent cache and handle and provides a separate MPs queue for customer-service communication. The use of instances ensures that customers of multiple pipelines can use the same named pipeline at the same time.

Microsoft Windows NT, Windows 2000, Windows 95, and Windows 98 all support named pipes (excluding Windows CE ), however, only Windows NT and Windows 2000 support server-side Named Pipe Technology. A named pipe can establish reliable data communication between different processes of the same computer or between different processes of different computers across a network. If the connection is interrupted, both parties can immediately receive the disconnection information. The command pipeline is a mechanism designed around the Windows File System. It uses the named pipe File System (npfs) interface. The readfile () and writefile () functions are used to send and receive data. In terms of design, since the named pipe also uses the Microsoft network provider (msnp) redirection, it does not need to involve the details of the underlying communication protocol. The naming pipeline also makes full use of the built-in security features of Windows NT and Windows 2000, so the communication security is relatively good.

  Naming rules and communication modes

Each named pipeline has a unique name to distinguish it from other named pipelines that exist in the system's named object list. The MPs Queue Server specifies a name when calling the createnamedpipe () function to create one or more instances of the named MPs queue. For the MPs queue client, specify the MPs queue name when calling the createfile () or callnamedpipe () function to connect to a named MPs queue instance. The naming rules of the named pipeline are similar to those of the mail slot, and the IDs are also in the UNC format:

// Server/pipe/[path] Name

Specifically, the first part // server specifies the name of the server, named pipeline service is created on this server, its string part can be expressed as a decimal point (indicating the local machine), asterisk (the current network field) domain name or a real service. The second part/pipe is an unchangeable hard-coded string like/Mailslot in the mail slot to indicate that the file belongs to npfs; the third part/[path] Name enables the application to uniquely define and identify the name of a named pipeline, and to set multi-level directories.

The named pipe provides two basic communication modes: byte mode and message mode. You can use pipe_type_byte and pipe_type_message when creating a named pipe in createnamepipe. In byte mode, information flows between customers and servers in the form of continuous byte streams. This means that for client applications and server applications, the number of bytes read or written from the pipeline cannot be accurately known within any specific period of time. In this communication mode, after one party writes a certain number of bytes to the pipeline, it cannot ensure that the other party can read the same number of bytes. In message mode, the client and server send and receive data through a series of discontinuous data packets. Each message sent from the pipeline must be read as a complete message.

Use Named Pipe

When the MPs Queue Server calls the createnamedpipe () function for the first time, the nmaxinstance parameter is used to specify the maximum number of MPs queue instances that can coexist. The server can repeatedly call the createnamedpipe () function to create a new instance of the MPs queue until the maximum number of instances is reached. The following is a prototype of the createnamedpipe () function:

Handle createnamedpipe (
Lptstr lpname, // pointer to the pipe name
DWORD dwopenmode, // pipeline open mode
DWORD dwpipemode, // pipe mode
DWORD nmaxinstances, // maximum number of instances
DWORD noutbuffersize, // output cache size
DWORD ninbuffersize, // enter the cache size
DWORD ndefatimetimeout, // timeout setting
Lpsecurity_attributes lpsecurityattributes // Security Attribute pointer

If an instance MPs queue can be used before the defined value is changed to zero, the MPs queue is created successfully and a MPs queue handle is returned to listen for connection requests from the client. On the other hand, the client uses the waitnamedpipe () function to wait for the server process to connect to the instance from the customer. If an MTS queue is available for connection before the timeout value is zero, the function returns a successful response and calls the connection to the server by calling createfile () or callnamedpipe. At this time, the server will accept the customer's connection request and establish a connection. The connectnamedpipe () function called by the server waiting for the client to establish a connection will also return a successful result.

In terms of the call sequence, the client first makes the createfile () of the server successfully created the instance within a limited time period through waitnamedpipe (), and then the two parties connect to the instance through connectnamedpipe () and createfile, after a file handle is returned for communication, the customer and the service provider can communicate with each other.

After a connection is established, the client and server can exchange information with each other through readfile () and writefile () and the obtained pipeline handle in the form of file read/write. When the communication between the client and the server ends or the client needs to be disconnected for some reason, the client calls the closefile () function to close the open pipeline handle, and the server then calls the disconnectnamedpipe () function. Of course, the server can also terminate the connection by unilaterally calling disconnectnamedpipe. Call closehandle () after terminating the connection to close the pipeline. The program list below is the simple program implementation code for the pipe server to communicate with the client based on the naming method described above:

M_hpipe = createnamedpipe ("//. // pipe // test", pipe_access_duplex, pipe_type_byte | pipe_readmode_byte, 1, 0, 0, 1000, null); // create a named pipe
If (m_hpipe = invalid_handle_value)
M_smessage = "An error occurred while creating the named pipe! ";
Else {
M_smessage = "the named MPs queue is created successfully! ";
Afxbeginthread (readproc, this); // enable the thread

Because the connectnamedpipe () function will wait infinitely when no client is connected to the server, to avoid blocking the main thread, it opens a subthread readproc:

Uint readproc (lpvoid)
Char buffer [1024]; // data cache
DWORD readnum;
Cserverview * pview = (cserverview *) lpvoid; // obtain the view handle
If (connectnamedpipe (pview-> m_hpipe, null) = false) // wait for the connection from the client
Closehandle (pview-> m_hpipe); // close the pipe handle
Pview-> m_smessage = "An error occurred while establishing a connection with the client! "; // Display information
Pview-> invalidate ();
Return 0;
} Else {
Pview-> m_smessage = "establish a connection with the client! "; // Display information
Pview-> invalidate ();
// Read data from the MPs queue
If (readfile (pview-> m_hpipe, buffer, sizeof (buffer), & readnum, null) = false)
Closehandle (pview-> m_hpipe); // close the pipe handle
Pview-> m_smessage = "An error occurred while reading data from the MPs queue! "; // Display information
Pview-> invalidate ();
} Else {
Buffer [readnum] = '/0'; // display received information
Pview-> m_smessage = cstring (buffer );
Pview-> invalidate ();
Return 1;

After the customer establishes a connection with the server, connectnamedpipe () will return and the following statement can be executed. The subsequent readfile () will be responsible for reading the data written into the pipeline by the customer. After all the operations are completed, the server can terminate the connection by calling the disconnectnamedpipe () function:

If (disconnectnamedpipe (m_hpipe) = false) // terminate the connection
M_smessage = "An error occurred while terminating the connection! ";
Closehandle (m_hpipe); // closes the pipe handle
M_smessage = "Connection terminated successfully! ";


Cstring message = "[test data, sent by the client]"; // data to be sent
DWORD writenum; // The Data Length sent
// Wait for connection to the server
If (waitnamedpipe ("//. // pipe // test", nmpwait_wait_forever) = false)
M_smessage = "waiting for connection failure! "; // Display information
Invalidate ();
// Open the MPs queue handle
Handle hpipe = createfile ("//. // pipe // test", generic_read | generic_write, 0, null, open_existing, file_attribute_normal, null );
If (hpipe = invalid_handle_value)
M_smessage = "pipeline opening failed! "; // Display information
Invalidate ();
} Else {
M_smessage = "pipeline opened successfully! "; // Display information
Invalidate ();
// Write data to the MPs queue
If (writefile (hpipe, message, message. getlength (), & writenum, null) = false)
M_smessage = "An error occurred while writing data to the MPs queue! "; // Display information
Invalidate ();
} Else {
M_smessage = "data is successfully written to the MPs queue! "; // Display information
Invalidate ();
Closehandle (hpipe); // closes the pipe handle


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.