Windows Inter-process communication Category: Network programming 2011-12-27 09:56 9372 People read Comments (2) Collection ReportWindows DLL server sockets socket API
pick to: with the increasing demand for applications, single-process applications have been unable to meet people's requirements in many situations. Writing multi-process/Multi-thread program has become an important feature of modern programming, and communication between processes is unavoidable in multi-process programming. Microsoft Win32 APIIt provides a variety of methods for inter-process communication, expounds the characteristics of these methods comprehensively, and compares and analyzes them, hoping to provide a reference for readers to choose communication methods.
Key Words Process Process CommunicationIPC Win32 API
1 process and process communication
A process is a program loaded into memory and ready to execute, each with a private virtual address space, with code, data, and the system resources it can utilize(such as documents, pipelines, etc.)composition. Multi-Process/Multithreading isWindowsa basic feature of the operating system. Microsoft Win32Application Programming Interface(Application Programming Interface, API)provides a large number of mechanisms to support data sharing and exchange between applications, which are activities called interprocess communication(interprocess communication, IPC), process communication refers to the data sharing and data exchange between different processes.
just because of the useWin32 APIThere are many ways to communicate the process, how to choose the appropriate communication mode becomes an important issue in application development, the following article willWin32analysis and comparison of several methods in process communication.
2 Process Communication Methods
2.1 file map
File Mappings (memory-mapped files) Allows the process to treat the file contents as a memory of the process address. 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.
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. The
application has three ways 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) naming a file mapping: The first process can give the object a name (different from the file name) when it establishes the file-mapping object. 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 effective way to share data across multiple processes with better security. But 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.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 and the Clipboard support both standard data formats, such as text, bitmaps, and 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 to Exchange data:
(1) Cold chain: Data Exchange is a one-time transfer, the same as the Clipboard.
(2) Win Chen: The server notifies the customer when the data is exchanged, and the customer must request new data.
(3) HOT chain: The server automatically sends 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.
attached:
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 ();
Windows Inter-process communication