interprocess communication-mail slots and named Pipes D

Source: Internet
Author: User
Tags function prototype readfile

Interprocess communication refers to the sharing of data between two or more processes in the system through a third party.

1. Postal slots.

The mail slot is a one-way communication mechanism provided by Window System. That is, a party in a process can only write or read data, while the other party can only read or write data. Through the mail slot, you can achieve a one-to-many or cross-network process communication. But the amount of data sent by the mail slot is very small, generally only about 400KB.


Mail slot creation function Createmailslot, function prototype:

HANDLE Createmailslot (  lpctstr lpname,                            //mailslot name  DWORD nmaxmessagesize,                     //maximum message size  DWORD lreadtimeout,                        //Read time-out interval  lpsecurity_attributes lpsecurityattributes// Inheritance option);

The parameter lpname represents the name of the postal slot. The postal slot name format is"\\.\mailslot\name". Where name indicates the name of the postal slot. In VC, the format is"\\\\.\mailslot\name", if it is running on a different host, the"."Replace the host name with the other.

The parameter nmaxmessagesize specifies the maximum number of message sizes sent or received by the mail slot. The general setting is 0, which indicates that the message size is any value.

The parameter lreadtimeout indicates the time that the program read operation exceeded. If the parameter is 0, the function returns immediately when there is no message in the mail slot. If the parameter is mailslot_wait_forever, it means waiting forever until there is a message.

The parameter lpsecurityattributes is a pointer to the struct security_attributes, which represents the security properties of the mail slot. Generally null, which represents the default security attribute.


Read and write operations by function ReadFile () and function WriteFile ().


The following is the code implemented by the C language:

"Service Side":

#include <stdio.h> #include <windows.h>int main () {HANDLE Mail;mail =:: Createmailslot ("\\\\.\\mailslot\\ Mysolt ", 0, Mailslot_wait_forever, NULL);//create mail slot if (mail = = Invalid_handle_value) {printf (" Create mail slot failed!\r\n "); CloseHandle (mail);} else{printf ("Create mail slot successfully, reading data ...!!") \ r \ n "); char text[200];D word readtext;if (ReadFile (mail, text, &readtext, NULL))   //Read Data {printf ("%s\r\n ", text);} else{printf ("Read data failed!\r\n");}} CloseHandle (mail); Sleep (+); return 0;}
"Client":

#include <stdio.h> #include <windows.h>int main () {HANDLE Mail;char text[] = "Hello, this is a text";D Word write Text;mail = CreateFile ("\\\\.\\mailslot\\mysolt", Generic_write, File_share_read, NULL, open_existing, File_attribute _normal, NULL);       Open File if (mail = = Invalid_handle_value) {printf ("Mail slot open failed!\r\n");} Else{if (WriteFile (mail, text, sizeof (text), &writetext, NULL))   //write file {Sleep ();p rintf ("Write Data successfully!\r\n");} else{printf ("Write Data failed!\r\n");} CloseHandle (mail);} Sleep (+); return 0;}

Test examples:



2. Name the pipe.

Named pipes transmit data in a connection-based and reliable way, so named pipes transmit data only one-to-one transmissions.


The named pipe creation function is createnamepipe ();

The function prototypes are:

HANDLE createnamedpipe (  lpctstr lpname,                             //Pipe name  DWORD Dwopenmode,                           //Pipe open mode  DWORD Dwpipemode,                           //Pipe-specific modes  DWORD nmaxinstances,                        //maximum number of instances  DWORD Noutbuffersize,                       //Output buffer size  DWORD ninbuffersize,                        //input buffer size  DWORD Ndefaulttimeout,                      //time-out interval  lpsecurity_attributes lpsecurityattributes  //SD);

The parameter lpname represents the name of the named pipe that was created. It is generally "\\\\.\\pipe\\pipename".

The parameter Dwopenmode represents the open mode of the named pipe, including the access mode, the safe access mode of the pipe handle, and the overlap method.

The parameter Dwpipemode represents the type, read, and wait mode of the handle pipeline.

The parameter nmaxinstance represents the maximum number of instances the pipeline can create.

The parameter noutbuffersize represents the size of the output buffer.

The parameter Ninbuffersize represents the size of the input buffer.

The parameter ndefaulttimeout represents the time-out value, and the same pipe must be used by different instances to take the same timeout value.

The parameter lpsecurityattributes is a pointer to the struct security_attributes that represents the security properties of the named pipe.


The connection named pipe waits for the client's connection request with the function connectnamedpipe ().

Function Prototypes:

BOOL connectnamedpipe (  HANDLE hnamedpipe,          //HANDLE to named pipe  lpoverlapped lpoverlapped   // OVERLAPPED structure);

Use the function waitnamedpipe () to determine whether a named pipe created by the server is available.

function prototype;

BOOL waitnamedpipe (  lpctstr lpnamedpipename,  //pipe name  DWORD ntimeout            //time-out interval);

The following is an example of a C language implementation:

Service side:

#include <stdio.h> #include <windows.h>int main () {HANDLE hpip;overlapped ovi = {0};                                 Define struct-body variable char buf[200];D Word readbuf;hpip = createnamedpipe ("\\\\.\\pipe\\pipename", Pipe_access_duplex, Pipe_type_ BYTE, pipe_unlimited_instances,1024, 1024x768, 0, NULL);                             Create the named pipe printf ("Create pipeline successfully, wait for client connection!\r\n"); if (:: Connectnamedpipe (Hpip, &ovi))                   //Wait for connection, block in this {printf ("Client connection succeeded!\r \ n ");p rintf (" reading Data!\r\n "), if (:: ReadFile (Hpip, buf, $, &readbuf, NULL))   //Read Data {printf (" Read data successfully!\r\n "); printf ("%s\n", buf);} else{printf ("Read data failed!\r\n");}} return 0;}
Client:

#include <windows.h> #include <stdio.h>int main () {HANDLE hpip;overlapped ovi = {0};char buf[200] = " Named pipe test data: Hello ";D word readbuf;                                            Define struct variable printf ("Connecting Named Pipes!\r\n"); if (:: Waitnamedpipe ("\\\\.\\pipe\\pipename", Nmpwait_wait_forever))  // Connect Named pipes {Hpip = CreateFile ("\\\\.\\pipe\\pipename", Generic_read | Generic_write, 0, NULL, open_existing, file_attribute_normal, null);                             Open Named Pipes if (Hpip = = Invalid_handle_value) {printf ("Open Named Pipes failed!\r\n");} Else{if (WriteFile (Hpip, buf, sizeof (BUF), &readbuf, NULL)       //write Data {printf ("Write Data successfully!\r\n");} else{printf ("Write Data failed!\r\n");}}} elseprintf ("Connection named pipe failed!\r\n"); return 0;}


Test examples:



interprocess communication-mail slots and named Pipes D

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.