Windows inter-process communication

1 process and interprocess communication

  Program into memory and the process is ready for execution, each process has a private virtual address space, by the code, data and system resources available to it ( such as files, pipes, etc. ) components. Multi-process / multi-thread is Windows a basic feature of the operating system. Microsoft Win32 application programming interface (Application Programming Interface, API) provides a lot of support between the application and data sharing mechanisms for the exchange of the exercise of these activities called interprocess communication mechanisms (InterProcess Communication, IPC) , interprocess communication refers to different processes data sharing and data exchange.   Because of the use of Win32 API processes communicating a variety of ways, how to choose the appropriate means of communication has become an important issue in application development, the following article will Win32 several methods of communication process to be analyzed and compared.

 

2 interprocess communication method

2.1 file mapping   file mappings (Memory-Mapped Files) can process the contents of the file as a memory address range process as treated. Thus, the process does not use the file I / O operations, the pointer operation can be simply read and modify the contents of the file. Win32 API allows multiple processes to access the same file mapping object, 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, enables shared data in the file. Application There are three ways to enable multiple processes to share a file mapping object. (1) Inheritance: The first process established file mapping object, its children inherit a handle to the object. (2) Name the file mapping: the first process can assign a name to the object when creating the file mapping object (the file name may differ). The second process can open the file mapping object by name. In addition, the first process can also put their names passed to the second process through some other IPC mechanisms (named pipes, mail slots, etc.). (3) handle copy: The first process established file-mapping object, and then pass through other IPC mechanisms (named pipes, mail slots, etc.) to the second object handle process. The second process duplicates the handle to get access to the file-mapping object. File mapping is a very effective method of sharing data between multiple processes, there is better security. However, file mapping can only be used between processes on the local machine can not be used in the network, and the developer must also control the synchronization between processes .

2.2 Shared Memory   in the Win32 API shared memory (Shared Memory) is actually a special case of file mapping. Process when creating a file mapping object with 0xFFFFFFFF instead of the file handle (HANDLE), it means that the corresponding file mapping object is accessed from the operating system page file memory, other processes to open the file mapping object can access the memory block. Since the memory is shared with the file mapping implementation, so it has a good safety, can only run in between processes on the same computer .

2.3 anonymous conduit   pipe (Pipe) is a communication channel having two ends: one end of the process can handle and the other end has a handle-process communication. Conduit may be unidirectional - end is read-only, write only the other endpoint; may also be a two-way - the two end points of the pipe both readable and writable. Anonymous pipe (Anonymous Pipe) is between the parent and child processes, with or without the name of the one-way pipeline to transfer data between two sub-processes of the same parent process. Usually created by a parent process piping, and then inherited by the child process to the channel of communication endpoint handle to read or write endpoint handle, and then communicate. The parent process can also create two or more anonymous pipe inherit read and write handles child process. These sub-processes can communicate directly using a pipe, not required by the parent process.   Anonymous pipe is an effective way to achieve sub-process standard I / O redirection on a single machine, it can not use the Internet, can not be used between two unrelated processes.

2.4 Named Pipes   Named Pipes (Named Pipe) pipe is unidirectional or bidirectional communication between the server and the one or more client processes. Anonymous pipe is different from the named pipe can be used between unrelated processes and different computer, specify a name server to establish a named pipe to it, any process can open the other end of the pipe by the name, according to the given permissions and server processes communicate. Named Pipes provides a relatively simple programming interface, does not make the communication more difficult than between two processes on the same computer network to transfer data, but if you want to communicate simultaneously with a plurality of processes it powerless.

2.5 mail slot   mail slot (Mailslots) provides inter-process one-way communication capability , any process can create a mail slot into a mail slot server. Other processes, known as the mail slot of customers , can send messages through the mail slot name to the mail slot server process. Incoming message has been placed in the mail slot until the server process to read it so far. A process server can be either the mail slot mail slot can also be a client, so you can create multiple mail slots two-way communication between processes.   By mail to the mail slot groove may be on the local computer, the mail slot or designated areas on the other network computers have the same name in the mail slot to send a message on all computers. Broadcast communication message length can not exceed 400 bytes, the length of the non-broadcast message is restricted mailslot server specified by the maximum message length.   Mail slots and named pipes similar, but which transmits data over unreliable datagram (e.g. UDP packet TCP / IP protocol) is completed, once the network error can not be guaranteed message is correctly received, the named pipe to transfer data is It is built on the basis of reliable connection. However, to simplify message groove and programming interface to the network within a specified area of all capabilities of the computer of the broadcast message, the mail slot after all applications send and receive messages to an alternative.

2.6 clipboard  clipboard (Clipped Board) is the essence of the Win32 API set for data transmission functions and messages , provide an intermediate data sharing between applications Windows, Windows established cut (copy) - Paste the mechanism provides a convenient way to share data between different formats for different applications. When the user performs a cut or copy operation in the application, the application of the selected data on the clipboard with one or more formats. And any other application that can pick up the data from the clipboard, choose the format from the given format. The clipboard is a very loose exchange medium, can support any data format, each format identified by an unsigned integer, the standard (predefined) clipboard format, the value is defined constants Win32 API; non-standard format can use Register clipboard format function to register a new clipboard format. Exchange data using clipboard data format simply coincides with or can be converted into a format line. But clipboard can only be used in Windows-based program can not be used on the network.

2.7 DDE   Dynamic Data Exchange (DDE) is used for shared memory inter-process communication in the form of data exchange between applications. When DDE applications can use the one-time data transmission, it may occur as new data, dynamic data exchange between applications by sending updated value. DDE and the clipboard as both support standard data formats (such as text, bitmaps, etc.), and can support their defined data format. But their data transfer mechanism is different, a significant difference is almost always clipboard operations as a response to the user-specified-time operations - such as selecting Paste command from a menu. Although DDE can also be initiated by the user, but it does not have to continue to play the role of general user further intervention. DDE data exchange three ways: (1) cold chain: one-time data exchange of data transmission, the same as the clipboard. (2) Temperature Chain: when the data exchange server notifies the client, then the client must request a new data. (3) Thermal strand: when the data exchange server automatically sends data to the client. DDE exchange may occur between stand-alone or network applications of different computers. Developers can also define custom DDE particular object of IPC data format between applications, they have a more tightly coupled communication requirements. Most Windows-based applications support DDE.

2.8 Object Linking and Embedding   applications using Object Linking and Embedding (OLE) AND MANAGEMENT compound documents (document data formats from a variety of compositions), OLE provides to make an application easier to invoke other applications edited data services. For example, OLE supported word processor can be nested spreadsheet, OLE library may launch the spreadsheet editor automatically 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 spreadsheet editor extended into the word processor, whereas if DDE, the user wants to explicitly start the spreadsheet editor. The same technology with DDE, most Windows-based applications that support OLE technology.

2.9 Dynamic Link Library   Win32 dynamic link library (DLL) in the global data may be calling all processes shared DLL, which gave inter-process communication has opened up a new way, of course, pay attention to synchronization problems when accessing. Although inter-process data can be shared by the DLL, but the data security point of view, we do not advocate this approach, better use of shared memory with access control.

2.10 Remote Procedure Call   Remote Procedure Win32 API calls provided (RPC) enables applications to use remote function calls, making processes communicating on the network using RPC as simple as function calls. RPC can be used in both stand-alone between different processes can also be used in the network. Since RPC Win32 API provided obey OSF-DCE (Open Software Foundation Distributedstandard. So as prepared by the Win32 API RPC applications to application communication RPC DEC support and on other operating systems. Use RPC developers can build high-performance, tightly coupled distributed applications.

2.11 NetBios function   Win32 API provides functions for handling low-level network NetBios control, which is mainly written for IBM NetBios and Windows system interface. Unless those applications have special requirements of the low-level network functions, other applications should not use NetBios function for interprocess communication.

Sockets 2.12   Windows Sockets specification is a set of network programming interface under Windows UCBerkeley University of BSD UNIX in the popular Socket interface paradigm defined. In addition to the original Berkeley Socket library functions, it also extended a set of functions for Windows that allows programmers to take full advantage of Windows message mechanism for programming. Now more and more by Sockets implementation process communication network applications, mainly because of cross-platform Sockets much better than other IPC mechanisms, in addition WinSock 2.0 not only supports TCP / IP protocol, but also supports other protocols (such as IPX). Sockets The only drawback is that it is supported by the underlying communications operation, which makes it very convenient for simple data transfer between the single process, this case will be described below using the message WM_COPYDATA more appropriate.

2.13 WM_COPYDATA news   WM_COPYDATA is a little-known but very powerful message. When an application transmitting data to another application, the sender simply use SendMessage function call, the destination window parameter is the handle, the starting address of data transfer, WM_COPYDATA message. Just like other receiver processing WM_COPY DATA message as message processing, sending and receiving sides so to achieve data sharing. WM_COPYDATA is a very simple way, it is actually implemented by the underlying file mapping. The disadvantage is that flexibility is not high, and it can only stand-alone environment for the Windows platform.

 

3 Conclusion

  Win32 API provides such a variety of options for the application to achieve inter-process communication, so developers how to choose it? Usually before deciding which method to use IPC should consider the following questions: (1) the application is in a stand-alone environment or work in a networked environment.

 

Attachment:

When I learned windows programming, interprocess communication on how to always feel very mysterious, many ways to introduce on the network, but few have introduced a system, a wide variety of people always say confused, here I sort out the various communication methods, combing the advantages and disadvantages of these methods, hoping to play a valuable role for you Tell me. Inter-process communication technologies have non-standard: Windows news, memory mapping, memory sharing and so on.

1. Windows messages to achieve inter-process communication. The receiving process and the process of sending a message to be defined in the same message. However, if the sender is only sending a message, the message sender can not implement the mapping, without defining message response function. Recipient and the corresponding need to define a mapping function. Since inter-implemented process definition message communication defect is due to the transmission parameters of the message is a long integer lParam, therefore, only transfer data shaping, but can not be passed string. There is a possible idea is to pass the address of the string is located, then the process handle obtained by another program the sender, and a function ReadProcessMemory WriteProcessMemory memory operation to read the contents of the sender.

2. The message WM_COPYDATA MFC defined custom message in fact common messaging with similar, except that the transfer structure is a pointer pointing to COPYDATASTRUCT string to be transmitted is saved in this structure. A first variable dwData of this structure can be set to zero. After the news that the different ideas of the above is to obtain a pointer to the structure, the process of receiving no other treatment can get pointers to the data, if the same communication in the same process. Also, note that the message sometimes can not accept the desired length is obtained, it is possible to receive only a portion. Thus, this method is suitable only for small amounts of data transfer.

3. Process conjecture memory read and write functions substantially the same as the rear portion of the gains methods. The key is to use the GlobalAlloc () or VirtualAllocEx to allocate memory space to store data. Data is written to the recipient's process memory, and then went on to address a message to tell his data. Since the application is in memory of the sender, then sleep better to wait some time before application to get VirtualFreeEx memory. GlobalAlloc () or VirtualAllocEx reason in the memory space of another process to apply for memory, which can be why the above can be achieved. In other words, the sender is not in its own memory space for memory, but the receiver process memory space to allocate memory. Then input data is written. Of course, you can also process space to the sender application memory, read by the recipient to the process of reading and writing across the way. It's just different approach.

4. The benefits of using memory-mapped file memory mapping method is that you can treat a file as a memory area to be treated. When files can be read and written to different processes. Since that memory area like a file, then this memory area can be used by different processes to read and write.

5. Use the DLL Win32 DLL to communicate not only share code share data, different processes load the same DLL files, DLL code only a loaded into memory, this refers only to the same piece of code loaded DLL files, if the same DLL file under a different drive letter, nor is it the same DLL, but multiple copies of the same DLL. Win16 DLL is loaded into the system memory, so call it a process that is accessible to its global variables, so you can easily achieve inter-process communication. But for win32 DLL, the operating system will map the DLL to call it the process's address space each, DLL becomes part of the process. Can use the following method to the DLL is set to the data area shared area.

#pragma data_seg ( "SHARED") // define a shared data segment is called SHARED

char m_strString [256] = TEXT ( ""); // data sharing. Particular attention needs to be initialized, because the compiler will uninitialized variable is stored in the data segment bss.

volatile bool bInCriticalSection = FALSE; // Flag synchronization

#pragma data_seg ()

#pragma comment (linker, "/ SECTION: SHARED, RWS") // will be shared data segment inform the compiler.

CCriticalSection cs; // critical section, above synchronous control of the synchronization control.

 

6. Use the operating system clipboard communicate using the clipboard is a smaller overhead interprocess communication mechanisms. Clipboard is the principle mechanism, the system clipboard is reserved for a global memory , the data used to temporarily hold data exchange between processes. Provide data processes need to create a global memory block, and then move the data to be transferred or copied to the memory block. Receiving process need handle this memory block, read data is completed.

The following procedures indicate how the clipboard to write data

StrData = m_strClipBoard CString; // get the data. 

// open system clipboard. 
IF (OpenClipboard ()!) Return ; 

// . Prior to use, the system clipboard empty 
the EmptyClipboard (); 

// allocate a memory size equal to the copied the size of the character string, returns a handle to the memory controller. 
the HGLOBAL hClipboardData; 

hClipboardData = the GlobalAlloc (GMEM_DDESHARE, strData.GetLength () + . 1 ); 

// memory control handle lock, return specific data value that points to the memory where the control handle pointer format. 
char * pchData; pchData = ( char * ) the GlobalLock (hClipboardData); 

// the value of the local variable assigned to global memory. 
strcpy (pchData, LPCSTR (strData)); 

// to control locking of a global memory handle to unlock. 
GlobalUnlock (hClipboardData);

// through global memory handle the data to be copied onto the clipboard. 
The SetClipboardData (the CF_TEXT, hClipboardData); 

// after use to close the clipboard. 
CloseClipboard ();

From the clipboard to read data code is as follows:

// Open the system clipboard. 
IF (OpenClipboard ()!) Return ; 

// determines whether the data on the clipboard data format is specified. 
IF (IsClipboardFormatAvailable (the CF_TEXT) || IsClipboardFormatAvailable (CF_OEMTEXT)) 
{ 
    // from the clipboard the data obtained. 
    hANDLE hClipboardData = GetClipboardData (the CF_TEXT);
     // by the handle to lock the memory, to obtain a pointer to the specified data format. 
    char * pchData = ( char * ) the GlobalLock (hClipboardData);
     // local variable to obtain data. 
    m_strClipBoard = pchData;
     // to unlock the memory handle. 
    the GlobalUnlock (hClipboardData); 
} 
the else  
{
    AfxMessageBox ( "IS NO text there (the ANSI) The Data ON a Clipboard. " ); 
} 

// after use to close the clipboard. 
CloseClipboard ();
 // update data. 
UpdateData (FALSE);

 

 

7.DDE (Dynamic Data Exchange) Dynamic Data Exchange now Microsoft has stopped the development of this technology, preserving only support. Advanced communications technology front are several basic interprocess communication techniques, messages pipeline (Message Pipes), mail slot (Mail slots), and Sockets (Sockets) is actually more common method, in addition to these types of advanced communications like the above method like the local system to communicate between processes it may also be used for remote communication between different systems.

8. Message Pipes Message Pipes divided into anonymous pipe (anonymous Pipes), and named pipes (Named Pipes), anonymous pipes mainly used for communication between the child and the parent process on the local system he started. Some senior named pipe can be between processes on different systems and then communicate, because UNIX, LINUX and so support this technology, so named pipe technology is an ideal C / S structure communication technologies. Named Pipes principle, a process the data into the pipeline, the pipeline often know another name to the data removed. Others do not know the name of the pipeline can process data can not be removed. Therefore, the pipeline is actually shared between a process memory. Create a pipeline pipe server process is called, is the process pipeline links the client. Function to create a pipeline is HANDLE CreateNamedPipe (....); Connecting pipes CallNamedPipe (); reading or writing data midfielder close it ConnectNamedPipe (); the server is ready to connect to a client process piping, and wait until a customer connection until. DisconnectNamedPipe (); GetNamedPipeHandleState server with clients disconnect (); obtaining a named pipe state information GetNamedPipeInfo (); PeekNamedPipe acquires information of a named pipe (); copy data into a buffer SetNamedPipeHandleState () from a conduit; provided state information and a conduit pipe type the TransactNamedPipe (); message from a message read or write message WaitNamedPipe pipe (); that the server waits for connections from client instance. Basic flow communication pipe

(1) to establish a connection is established the server instance of a named pipe, and then through ConnectNamedPipe () function to listen for requests from clients obtained through ConnectNamedPipe function. This function can be set wait time. The client simply use function WaitNamedPipe () to connect to the server.

(2) Communication between establish communication connection between them, the pipe can be obtained by using a file handle for the ReadFile () and WriteFile ().

(3) the connection is terminated client calls CloseFile (), server-side calls DisconnectNamedPipe () terminates the connection. And the need to CloseHandle to close the pipeline.

9. 邮槽 communication

10. The communication socket socket communication process can be simply described as the main function call 5, socket (), bind (), Listen (), connect (), accept (). The main call server socket () , bind (), Listen (), accept (). The main client calls socket (), connect (). Data transfer is completed by both parties send () and recv (). There are five kinds of socket types, SOCK_STREAM, SOCK_DGRAM, SOCK_RAW, SOCK_SEQPACKET, SOCK_RDM.

10.1 Winsock program design process

(1) build environment program has two sets of functions Winsock programming, Socket1.1 and Socket2.0. Flexible mix. Socket2.0 have more powerful functions. Wherein the header comprises a library file and its corresponding file.

// Socket2.0
#include
#pragma comment (lib, “ws2_32.lib”);
 
// Socket1.1
#include
#pragma comment (lib, “wsock32.lib”);

(2) selection mechanism (asynchronous? Non-blocking?) The case of default blocking socket is created. Or WSAAsynSelect can select () function is to turn it into a non-blocking. Particular attention to the use of this function is non-blocking, not simply by the ioctlsocket () it then becomes blocked mode. That these two functions to change the blocking mode is different. ioctlsocket () is an asynchronous mode of the socket back to blocking mode again, but before to call the WSAAsynSelect () to cancel all asynchronous events, WSAAsynSelect (s, hWnd, 0,0);

(3) Starting and terminates the start function WSAStartup () to establish a connection Winsock DLL, terminating function WSAClearup () which terminates the DLL, these two functions must be used in pairs.

(4) error handling Winsock For compatibility with future multithreaded environments, two recent error number error handlers to get and set the current thread, namely WSAGetLastError () and WSASetLastError ();

Reproduced in: https: //www.cnblogs.com/RicoRico/archive/2013/03/10/2953208.html

Guess you like

Origin blog.csdn.net/weixin_33816946/article/details/93955637