Comparison of communication modes between processes (reprinted and collated)

Source: Internet
Author: User
Tags message queue ole semaphore terminates

Inter-process communication methods:

1. Piping (pipe) and famous pipe (named pipe):

Pipelines can be used for communication between affinity processes, which, in addition to having the functionality of a pipeline, allows for inter-process communication without affinity.

2. Signal (signal):

A signal is a simulation of the interrupt mechanism at the software level, it is a more complex mode of communication, used to notify the process that an event occurred, a process received a signal and the processor received an interrupt request effect can be said to be consistent.

3. Message Queuing (Messages queue):

Message queue is a link table of messages, it overcomes the disadvantage of limited signal in the last two modes of communication, and the process with write permission can add new information to message queue according to certain rules; a process that has Read permission on a message queue can read information from the message queue.

The message buffering communication technology is first put forward by Hansen, and its basic idea is that the information exchange between processes is realized by using the common message buffer in memory according to the "producer-consumer" principle.

Several message buffers are opened in memory to hold messages. Whenever a process sends a message to another process, it requests a message buffer, sends the prepared message to the buffer, and then inserts the message buffer into the message queue of the receiving process. Finally notifies the receiving process that the receiving process receives a notification from the sending mileage, extracts the message buffer from the message queue of the process, takes out the required information, and then sends the message buffer to the system irregularly. The system is responsible for managing the public message buffers and the delivery of messages.

A process can send messages to several processes, whereas a process can receive messages from different processes. Obviously, the process of Message Queuing is a critical section. When the sending process is adding a message to the message queue of the receiving process, the receiving process cannot go from the message queue to the message at the same time: vice versa.

The message buffer communication mechanism contains the following content:

(1) A message buffer, which is a data structure consisting of the following:
1. Message length
2. Message text
3. Sender
4. Message Queue pointers

(2) Message queue first pointer m-q, generally stored in the PCB.
(1) Mutual exclusion Semaphore M-mutex, the initial value of 1, for mutually exclusive access to the message queue, set in the PCB.
(2) The synchronous semaphore M-syn, the initial value is 0, for the message count, set in the PCB.
(3) Send message primitive send
(4) Receiving message origin receive (a)

4. Shared Memory:

This can be said to be the most useful inter-process communication method. It allows multiple processes to access the same piece of memory space, and different processes can see in time that the data in the shared memory is updated in the other process. This approach relies on some kind of synchronous operation, such as mutual exclusion and semaphore.

This communication pattern needs to address two issues: the first question is how to provide shared memory, and the second is the responsibility of the program developer for the mutual exclusion of public memory.

5. Signal Volume (semaphore):

It is used primarily as a synchronous and mutually exclusive means between processes and different threads of the same process.

6. Socket socket (socket);

This is a more general inter-process communication mechanism, it can be used for inter-process communication between different machines in the network, the application is very extensive.


/////////////////////////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////

1 process and Process communication

A process is a program that is loaded into memory and ready to execute, each with a private virtual address space, consisting of code, data, and the system resources (such as files, pipelines, and so on) that it can take advantage of. Multi-process/multithreading is a basic feature of the Windows operating system. The Microsoft WIN32 application Programming Interface (application Programming Interface, API) provides a number of mechanisms to support data sharing and exchange among applications that exercise activities called interprocess communication (interprocess Communication, IPC), process communication means data sharing and data exchange between different processes.
Because there are many ways to use the Win32 API for process communication, how to choose the proper communication mode becomes an important problem in application development, and the following article will analyze and compare several methods of process communication in Win32.

2 Process Communication Methods

2.1 File Mappings
File mapping (memory-mapped files) allows a process to treat the file content as if it were a block of memory in the process address range. Therefore, the process does not have to use file I/O operations and can read and modify the contents of the file with a simple pointer operation.
The Win32 API allows multiple processes to access the same file mapping object, and each process receives a pointer to memory in its own address space. By using these pointers, different processes can read or modify the contents of the file, enabling the sharing of the data in the file.
There are three ways for an application to share a file-mapping object with multiple processes.
(1) Inheritance: The first process establishes a file-mapping object whose child processes inherit the handle of the object.
(2) Named file Mapping: The first process can assign a name to a file-mapped object (different from the file name) when the object is created. The second process can open this file mapping object by this name. In addition, the first process can pass a name to the second process through some other IPC mechanisms (known as pipelines, mail slots, etc.).
(3) Handle replication: The first process establishes a file mapping object, and then passes the object handle to the second process through other IPC mechanisms (known as pipelines, mail slots, and so on). The second process copies the handle to gain access to the file-mapped object.
File mapping is a very efficient way to share data across multiple processes and has better security. However, file mappings can only be used between processes on the local machine, not on the network, and developers must also control synchronization between processes.

2.2 Shared Memory
Shared memory in the Win32 API is actually a special case of file mapping. When a process creates a file-mapped object with 0xFFFFFFFF instead of a file handle (HANDLE), it indicates that the corresponding file-mapping object accesses the memory from the operating system paging file, and the other process opens the file-map object to access the memory block. Because shared memory is implemented with file mappings, it also has better security and can only run between processes on the same computer.

2.3 Anonymous Pipelines
A pipe is a communication channel with two endpoints: a process with one end handle can communicate with a process that has a handle on the other end. The pipe can be unidirectional-one end is read-only, the other end is write-only, or bidirectional-the ends of the pipe are both readable and writable.
An anonymous pipe (Anonymous pipe) is a non-named one-way pipeline that transmits data between a parent process and a child process, or two child processes of the same parent process. The pipeline is typically created by the parent process, which then inherits the read endpoint handle or write endpoint handle of the channel, and then implements communication by the child process to communicate. The parent process can also establish two or more child processes that inherit the read and write handles of an anonymous pipe. These child processes can communicate directly using pipelines and do not need to pass through the parent process.
Anonymous pipelines are an effective way of implementing child process standard I/O redirection on a single machine, which cannot be used on-line or between two unrelated processes.

2.4 Named Pipes
A named pipe (Named pipe) is a one-way or two-way pipeline that communicates between a server process and one or more client processes. Unlike anonymous pipes, named pipes can be used between unrelated processes and between different computers, and when the server establishes a named pipe, it assigns a name to it, and any process can open the other end of the pipeline by that name, communicating with the given permissions and the server process.
Named pipes provide a relatively simple programming interface that makes it more difficult to transmit data over the network than between two processes on the same computer, but it is not enough to communicate with multiple processes at the same time.

2.5 Mail Slots
Mail Slots (mailslots) provide one-way communication between processes, and any process can establish a mail slot as a mail slot server. Other processes, called mail slots customers, can send messages to the mail slot server process by the name of the mail slot. The incoming message is kept in the mail slot until the server process reads it. A process can be either a mail slot server or a mail slot customer, so multiple message slots can be established to enable two-way communication between processes.
Mail slots enable you to send messages to a mail slot on the local computer, to a mail slot on another computer, or to a message slot with the same name on all computers in the specified network area. The message length of a broadcast communication cannot exceed 400 bytes, and the length of the non-broadcast message is limited by the maximum message length specified by the message slot server.
A message slot is similar to a named pipe, but it transmits data through unreliable datagrams (such as UDP packets in the TCP/IP protocol), and when a network error fails to guarantee that the message is received correctly, the named pipe transfer data is based on a reliable connection. However, the mail slot has a simplified programming interface and the ability to broadcast messages to all computers in the specified network area, so the mail slot is another option for the application to send and receive messages.

2.6 Clipboard
The Clipboard (clipped Board) is essentially a set of functions and messages in the Win32 API that are used to transfer data, providing a mediator for data sharing between Windows applications, and Windows has established cut (copy) -The paste mechanism provides a shortcut for sharing different format data between different applications. When a user performs a cut or copy operation in an application, the application places the selected data in one or more formats on the Clipboard. Any other application can then pick up the data from the Clipboard and choose the format that suits you in the given format.
The Clipboard is a very loosely exchanged medium that can support any data format, identified by an unsigned integer, for standard (predefined) clipboard formats, which are constants defined by the Win32 API, and register Clipboard for non-standard formats The Format function registers as the new clipboard formats. The data exchanged using the Clipboard can only be done in the same format or in a format. However, the Clipboard can only be used in Windows-based programs and cannot be used on the network.

2.7 Dynamic Data exchange
Dynamic Data Exchange (DDE) is an inter-process communication form that uses data exchange between applications that exist within a share. Applications can use DDE for one-time data transfer, or they can dynamically exchange data between applications by sending updated values when new data is present.
DDE, like the Clipboard, supports both standard data formats (such as text, bitmaps, and so on) and the data formats that you define. But their data transfer mechanism is different, one obvious difference is that clipboard operations are almost always used as a one-time response to user-specified actions-such as selecting the Paste command from the menu. Although DDE can also be initiated by the user, it continues to function generally without the user further intervention. DDE has three ways of exchanging data:
(1) Cold chain: Data Exchange is a one-time data transfer, the same as the Clipboard.
(2) Win Chen: When the data Exchange Server notifies the customer, then the customer must request new data.
(3) Heat chain: The server automatically sends the data to the customer when the data is exchanged.
DDE interchanges can occur between applications on a single machine or on a different computer in the network. Developers can also define custom DDE data formats for special purpose IPC between applications, which have more tightly coupled communication requirements. Most Windows-based applications support DDE.

2.8 Object Linking and embedding
The application uses object linking and embedding (OLE) technology to manage composite documents (documents consisting of multiple data formats), and OLE provides services that make it easier for an application to invoke other applications for data editing. For example, OLE supported word processors can nest spreadsheets, and the OLE library can automatically start the spreadsheet editor when the user wants to edit the spreadsheet. When the user exits the spreadsheet editor, the table has been updated in the original Word processor document. Here the Spreadsheet editor becomes an extension of the word processor, and if DDE is used, the user explicitly launches the spreadsheet editor.
As with DDE technology, most Windows-based Applications support OLE technology.

2.9 Dynamic Connection Library
The global data in the WIN32 Dynamic Connection library (DLL) can be shared by all processes that call the DLL, which in turn opens up a new way for interprocess communication and, of course, to be aware of synchronization issues when visiting.
Although you can use DLLs for inter-process data sharing, from a data security standpoint, we do not advocate this approach, and using shared memory with access control is a better approach.

2.10 Remote Procedure Calls
The Remote Procedure call (RPC) provided by the Win32 API enables applications to use remote calling functions, which makes process communication with RPC on the network as simple as a function call. RPC can be used either on a single machine or in a network.
Because the RPC provided by the Win32 API obeys the OSF-DCE (Open software Foundation distributed Computing Environment) standard. So RPC applications written through the Win32 API can communicate with DEC-capable RPC applications on other operating systems. Using RPC developers, you can build high-performance, tightly coupled distributed applications.

2.11 NetBIOS function
The WIN32 API provides NetBIOS functions for handling low-level network control, primarily writing interfaces to Windows for IBM NetBIOS systems. Unless applications with special low-level network functionality are required, it is best that other applications do not use NetBIOS functions for interprocess communication.

2.12 Sockets
The Windows Sockets specification is a set of network programming interfaces under Windows defined by the socket interface that is popular in the U.c.berkeley University BSD Unix paradigm. In addition to the original library functions of the Berkeley socket, a set of functions for Windows has been extended to enable programmers to fully utilize the Windows Messaging mechanism for programming.
More and more network applications are now implemented through sockets for process communication, mainly because sockets is much better cross-platform than other IPC mechanisms, and Winsock 2.0 supports not only the TCP/IP protocol, but also other protocols such as IPX. The only drawback of sockets is that it supports the underlying communication operations, which makes simple data transfer between single-machine processes less convenient, and the WM_COPYDATA message described below will be more appropriate.

2.13 Wm_copydata News
Wm_copydata is a very powerful but little-known message. When an app transmits data to another app, the sender simply uses the call SendMessage function, which is the handle to the destination window, the starting address for passing the data, and the WM_COPYDATA message. The receiver simply processes the WM_COPY data message just as it does with other messages, so that data sharing is achieved between the sending and receiving parties.
Wm_copydata is a very simple method, which is actually implemented by file mapping at the bottom. Its disadvantage is that the flexibility is not high, and it can only be used in a single machine environment for Windows platforms.

3 concluding remarks
The Win32 API provides so many options for application-interprocess communication, so how do developers make the choice? You should always consider the following questions before deciding which IPC method to use:
(1) Whether the application works in a network environment or in a stand-alone environment.

Report:
When I learn Windows programming, how to communicate between processes always feel very mysterious, the network introduced a lot of methods, but very few a system of introduction, a variety of statements let people always confused, here, I tidy up the communication methods, combing the advantages and disadvantages of these methods, I hope you can play a role in crossing. Non-standard interprocess communication technologies are: Windows Messaging, memory mapping, memory sharing, and so on.

1. Windows Messaging implements interprocess communication. Both the receiving process and the sending process of the message define the same message. However, if the sender is simply sending a message, the sender can not implement the message map without defining the message response function. The receiver needs to define the mapping and the corresponding function. The flaw in the implementation of custom messages for interprocess communication is that because the message's pass-through parameter is a long-shaped lparam, it can only pass the shaped data, not the string. One possible idea is to pass the address where the string is located, and then another program reads the content by getting the sender's process handle, using the function readprocessmemory with the writeprocessmemory to manipulate the sender's memory space.

2. Using MFC-defined WM_COPYDATA messages This message is actually similar to ordinary custom message communication, except that a pointer to the COPYDATASTRUCT structure is transmitted, and the string to be passed is stored in the struct. The first variable of this structure dwdata can be set to 0. The message is different from the idea above that, after acquiring the pointer to the struct, the receiving process does not need other processing to get the pointer data, as if it were communicating in the same process. Also note that the acceptance of the message sometimes does not get the required length, and may only be partially received. Therefore, the method is only suitable for passing in a small amount of data.

3. Using the process memory read-write function is basically the same as the method of the guess part behind. The key is to use GlobalAlloc () or VirtualAllocEx to allocate memory space to hold the data. Writes the data to the receiver's process memory and then sends a message to tell him the address of the data. Since it is the memory requested by the sender, it is better to wait for sleep for a certain amount of time before VirtualFreeEx the requested memory. GlobalAlloc () or VirtualAllocEx can implement a memory space in another process to request memory, which is why the above can be done. In other words, the sender does not request memory in its own memory space, but in the receiver process memory space to request memory. The input data is then written. Of course, you can also request memory in the sender's process space, and the receiver reads it through read-write across the process. It's just a different way of dealing with it.

4. Ways to use memory-mapped files The advantage of memory mapping is that you can treat a chunk of memory like a file. Files can be read and written by different processes. Since the memory area is like a file, the memory area can be read and written by different processes.

5. Using DLLs to communicate Win32 DLL can only share code can not share data, different processes loaded into the same DLL file, DLL code is loaded only one copy to memory, this only load a copy of code only refers to the same DLL file, if the same DLL file under different drive letter, It is not the same DLL, but more than one copy of the same DLL. The Win16 DLL is loaded into the system memory, so the process that invokes it can access its global variables, making it easy to implement interprocess communication. For Win32 DLLs, however, the operating system maps the DLL to the address space of each process that invokes it, and the DLL becomes part of the process. You can use the following method to set the data area of a DLL as a shared area.

#pragma data_seg ("shared")//define shared data segments named shared

Char M_strstring[256]=text (""); The shared data. In particular, it is important to note that initialization is required because the compiler saves uninitialized variables in the BSS data segment.

volatile bool Bincriticalsection=false; Synchronous marking

#pragma data_seg ()

#pragma COMMENT (linker, "/SECTION:SHARED,RWS")//The data segment that will be shared notifies the compiler.

CCriticalSection CS; The critical section, which controls synchronization, controls the synchronization problem.


6. Using the Clipboard provided by the operating system to implement communication using the Clipboard is one of the less expensive process communication mechanisms. The clipboard mechanism is that the Clipboard is a piece of global memory reserved by the system that is used to stage data exchanged between processes. The process that provides the data requires the creation of a global block of memory, which is then moved to or copied to the memory block. The receiving process needs to get a handle to this block of memory to complete the data read.

The following program indicates how to write data on the Clipboard

CString Strdata=m_strclipboard; Get the data.

Open the system Clipboard.

if (! OpenClipboard ()) return;

Empty the system Clipboard before use.

EmptyClipboard ();

Allocates a memory that is equal to the size of the string to be copied, returning the memory control handle.

Hglobal Hclipboarddata;

Hclipboarddata = GlobalAlloc (Gmem_ddeshare, Strdata.getlength () +1);

The memory control handle is locked and the return value is a pointer to the specific data format where the memory control handle resides.

char * PCHDATA; Pchdata = (char*) globallock (hclipboarddata);

Assigns the value of the local variable to global memory.

strcpy (Pchdata, LPCSTR (strdata));

Unlocks the global memory control handle for locking.

GlobalUnlock (Hclipboarddata);

The data to be copied is placed on the Clipboard through a global memory handle.

SetClipboardData (Cf_text,hclipboarddata);

Close the Clipboard When you are finished using it.

CloseClipboard ();


The code to read the data from the Clipboard is as follows:

Open the system Clipboard.

if (! OpenClipboard ()) return;

Determines whether the data on the Clipboard is the specified data format.

if (isclipboardformatavailable (cf_text) | | Isclipboardformatavailable (Cf_oemtext)) {

Gets the data from the Clipboard.

HANDLE hclipboarddata = GetClipboardData (cf_text);

Gets a pointer to the specified format data by locking the memory handle.

Char *pchdata = (char*) globallock (hclipboarddata);

Local variables to get the data.

M_strclipboard = Pchdata;

Unlocks the memory handle.

GlobalUnlock (Hclipboarddata);

}

Else

{

AfxMessageBox ("There is no text (ANSI) data on the Clipboard."); }

Close the Clipboard When you are finished using it.

CloseClipboard ();

Update the data.

UpdateData (FALSE);


7.DDE Dynamic Data exchange The current Microsoft has stopped developing this technology and has only retained support. Advanced communication technology is preceded by several basic process communication technologies, message pipelines (Messages Pipes), mail slots (mail slots), and sockets (Sockets) are the most common methods, these advanced communications in addition to the method like above to implement the local system process communication between , and can also be used to communicate between different systems remotely.

8. Message pipeline messages Pipes are also classified as anonymous pipes (anonymous Pipes), and Named Pipes (Named Pipes), which are used primarily for communication between the parent process on the local system and the child processes that he initiates. Named pipes are advanced and can be used for inter-process communication on different systems, because UNIX, Linux and so on support this technology, so named pipe technology is the ideal C/s structure communication technology. The principle of Named Pipes is that one process puts the data in the pipeline and the other knows the pipe name often to take the data away. Other processes that do not know the name of the pipe may not be able to take the data away. Therefore, the pipeline is actually a piece of shared memory between processes. The process that creates the pipeline is called the pipe server, and the process that links the pipeline is the client. The function to create the pipe is handle createnamedpipe (...); Connection pipe callnamedpipe (); Read in or write data to the lower waist to close it connectnamedpipe (); The server prepares a pipeline to connect to the client process and waits until the client is connected. Disconnectnamedpipe (); The server interrupts the connection to the customer getnamedpipehandlestate (); Gets the state information for a named pipe Getnamedpipeinfo (); Gets the information of a named pipe peeknamedpipe (); Copy data from a pipeline into a buffer setnamedpipehandlestate (); Sets the state information for a pipe and the pipe type transactnamedpipe (); Read messages or write messages from a message pipeline waitnamedpipe (); Causes the server to wait for an instance connection from the customer. Basic flow of pipeline communication

(1) Connection establishment server side through the Connectnamedpipe function to establish a named pipe instance, and then through the Connectnamedpipe () function to listen to the request from the client. This function can set the wait time. The client simply uses the function waitnamedpipe () to connect to the server.

(2) After the communication realizes the connection, it can use ReadFile () and WriteFile () to communicate with each other by getting the file handle of the pipeline.

(3) The connection terminates the client call CloseFile (), and the server-side call Disconnectnamedpipe () terminates the connection. And all require CloseHandle to close the pipe.

9. Mail Slot Communication

10. Socket communication Socket communication process can be simply described as, the main call 5 functions, Socket (), bind (), Listen (), connect (), accept (). The server side primarily calls socket (), bind (), Listen (), accept (). The client primarily calls the socket (), connect (). The data transfer between the two parties is done via send () and recv (). There are 5 main types of sockets, Sock_stream, Sock_dgram, Sock_raw, Sock_seqpacket, SOCK_RDM.

10.1 Winsock Programming process

(1) Program compilation environment has two sets of functions for Winsock program design, Socket1.1 and Socket2.0. can be mixed flexibly. The Socket2.0 function is more powerful. Contains one of the header files and their corresponding library files.

Socket2.0

#include

#pragma comment (lib, "Ws2_32.lib");

Socket1.1

#include

#pragma comment (lib, "Wsock32.lib");

(2) Selection mechanism (async?) Non-blocking? The blocked sockets are created by default. It can be made non-blocking by the Select or Wsaasynselect () function. It is important to note that this function can not be easily changed to block mode by using ioctlsocket () instead of blocking. That is to say, the two functions change the blocking pattern by the difference. Ioctlsocket () is to change the socket of the asynchronous pattern back to blocking mode, but before calling Wsaasynselect () cancels all asynchronous events, Wsaasynselect (s,hwnd,0,0);

(3) Start and stop the start function WSAStartup () The connection to the Winsock DLL, the terminating function Wsaclearup () terminates the DLL, and the two functions must be used in pairs.

(4) Error handling Winsock in order to be compatible with future multithreaded environments, two error handling functions are provided to get and set the current thread's recent error number, i.e. WSAGetLastError () and Wsasetlasterror ();

Comparison of communication modes between processes (reprinted and collated)

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.