Discussion on various communication methods between Windows Processes

Source: Internet
Author: User

Original article: http://blog.csdn.net/bjtbjt/article/details/7044266

1 Windows Process Communication Methods

A process is a program that loads memory and is ready to run. Each process has a private virtual address space, which consists of code, data, and system resources (such as files and pipelines) that it can use.
Multi-process/multi-thread is a basic feature of the Windows operating system. Microsoft Win32 application programming interface (API)
Provides a large number of mechanisms to support data sharing and exchange between applications. These mechanisms are used for activities called interprocess communication (IPC ),
Process communication refers to data sharing and data exchange between different processes.
Because there are many ways to use Win32 APIs for Process Communication, choosing an appropriate communication method becomes an important issue in application development,
The following section analyzes and compares several methods of Process Communication in Win32.

2 Process Communication Method

2.1 file ing

Memory-mapped files allows the Process to Treat the file content as a piece of memory in the process address range. Therefore, the process does not need to use file I/O operations,
You only need a simple pointer operation to read and modify the file content.
Win32 API allows multiple processes to access the same file ing object. Each process receives memory pointers in its own address space. By using these pointers, different processes can read or modify the file content,
To share data in files.
There are three ways for an application to share a file ing object with multiple processes.
(1) Inheritance: the first process establishes a file ing object, and its child process inherits the handle of the object.
(2) named file ing: when creating a file ing object, the first process can specify a name for the object (which may be different from the file name ). The second process can use this name to open the file ing object.
In addition, the first process can also pass the name to the second process through some other IPC Mechanisms (such as famous pipelines and email slots.
(3) handle replication: the first process establishes a file ing object, and then passes the object handle to the second process through other IPC Mechanisms (such as famous pipelines and email slots.
The second process copies the handle to obtain the access permission for the ing object of the file.
File ing is a very effective way to share data among multiple processes and provides better security. However, file ing can only be used between processes on the local machine and not on the network.
And developers must also control the synchronization between processes.

2.2 shared memory

In Win32 API, shared memory is a special case of file ing. When creating a file ing object, the process uses 0xffffffff to replace the file handle (handle ),

The corresponding file ing object accesses the memory from the file on the operating system page. Other processes can access the memory block by opening the file ing object. Because shared memory is implemented by file ing,
Therefore, it provides better security and can only run between processes on the same computer.

A. Set a shared memory area

Handle createfilemapping (handle, lpsecurity_attributes, DWORD, and lpcstr) // generates a file-mapping core object
Lpvoid mapviewoffile (
Handle hfilemappingobject,
DWORD dwdesiredacess,
DWORD dwfileoffsethigh,
DWORD dwfileoffsetlow,
DWORD dwnumberofbytestomap
); Get the pointer to the shared memory

B. Find out the shared memory
It is determined that the memory should be presented in a peer-to-peer manner. Each process must have the same capabilities, generate shared memory, and initialize it. Every process should call createfilemapping (),

Call getlasterror (). If the returned error code is error_already_exists, the process can assume that the shared memory domain has been opened and initialized by another process,

Otherwise, the process can reasonably consider itself as the first place, and then initialize the shared memory. In the client/server architecture, only the server process should generate and initialize the shared memory.
All processes should use
Handle openfilemapping (DWORD dwdesiredaccess,
Bool binherithandle,
Lptstr lpname );
Call mapviewoffile () to obtain the shared memory pointer.

C. synchronous processing (mutex)

D. Cleaning up bool unmapviewoffile (lpcvoid lpbaseaddress );

Closehandle ()

2.3 Anonymous Pipeline
Pipe is a communication channel with two endpoints: a process with one end handle can communicate with a process with the other end handle. The pipeline can be unidirectional-one end is read-only, and the other end is write-only;
It can also be a two-way pipeline where the two ends of the point is both readable and writable.

An anonymous pipeline (anonymous pipe) is a one-way channel that transfers data between a parent process and a child process, or between two child processes of the same parent process. Generally, the management path is created by the parent process,

Then, the sub-process to communicate inherits the read or write endpoint handle of the channel, and then implements communication. The parent process can also create two or more sub-processes that inherit anonymous pipeline read and write handles.
These sub-processes can communicate directly using pipelines without passing through the parent process.
An anonymous pipeline is an effective method for implementing sub-process standard I/O redirection on a single machine. It cannot be used online or between two unrelated processes.

2.4 Named Pipe
A named pipe (Named Pipe) is a one-way or two-way channel for communication between server processes and one or more client processes. Unlike anonymous pipelines, named pipelines can be used between unrelated processes and different computers,
When the server creates a named pipe, it specifies a name for it. Any process can use this name to open the other end of the pipe and communicate with the server process based on the given permissions.
The named pipeline provides a relatively simple programming interface, making it easier to transmit data over the network than to communicate with two processes on the same computer. However, it cannot communicate with multiple processes at the same time.

2.5 mail slot
Mailslots provides one-way communication between processes. Any process can establish a mail slot as a mail slot server. Other processes, called mail slot customers, can be assigned by the mail slot name
The mail trough server process sends messages. 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,
Therefore, you can establish multiple mail slots to implement bidirectional communication between processes.
You can use the mail slot to send messages to the mail slots on the local computer, the mail slots on other computers, or the mail slots with the same name on all computers in the specified network area.
The length of a message for a broadcast communication cannot exceed 400 bytes. The length of a non-broadcast message is limited by the maximum message length specified by the mail slot server.
The mail slot is similar to the named pipe, but it transmits data through unreliable datagram (such as UDP packets in TCP/IP protocol, once a network error occurs, messages cannot be correctly received,
The named pipe transmits data based on reliable connections. However, the mail slot provides simplified programming interfaces and the ability to broadcast messages to all computers in the specified network area,
Therefore, the mail slot is another option for applications to send and receive messages.

2.6 clipboard
Clipped board is essentially a group of functions and messages used to transmit data in Win32 APIs. It provides an intermediary for data sharing between Windows applications,
The cut (copy)-paste mechanism established in Windows provides a shortcut for different applications to share data in different formats. 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. Then, any other application can pick up data from the clipboard and select a suitable format from the given format.
The clipboard is a very loose exchange medium that supports any data format. Each format is identified by an unsigned integer in a standard (predefined) clipboard format, this value is a constant defined by Win32 API;
For non-standard formats, you can use the register clipboard format function to register the new clipboard format. The data exchanged using the clipboard can be consistent or both in the data format.
Convert to a certain 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 a form of inter-process communication in which data is exchanged between applications in the shared content. Applications can use DDE for one-time data transmission, or when new data appears,
Dynamically exchange data between applications by sending update values.
Like clipboard, DDE supports both standard data formats (such as text and bitmap) and custom data formats. However, their data transmission mechanisms are different. The obvious difference is that clipboard operations are almost
Always used as a one-time response to a user-specified operation-for example, select the paste command from the menu. Although DDE can also be started by the user, it continues to play a role without further user intervention. DDE has three data exchange methods:
(1) Cold Chain: data exchange is a one-time data transmission, the same as the clipboard.
(2) temperature chain: when data is exchanged, the server notifies the customer, and then the customer must request new data.
(3) Hot chain: when data is exchanged, the server automatically sends data to the customer.
DDE exchange can occur between applications of different computers in a single machine or network. Developers can also define custom DDE data formats for specific IPC between applications, which have more closely coupled communication requirements.
Most Windows-based applications support DDE.

2.8 object connection and embedding
Applications Use object connection and Embedding (OLE) technology to manage composite documents (documents composed of multiple data formats ), OLE provides services that make it easier for an application to call other applications for data editing.
For example, the word processor supported by Ole can nest workbooks. When you want to edit a workbook, the OLE library can automatically start the workbook editor. When you exit the workbook editor,
This table has been updated in the original word processor documentation. Here, the workbook editor becomes an extension of the word processor. If you use DDE, you need to start the workbook editor explicitly.
Similar to DDE technology, most Windows-based applications support OLE technology.

2.9 dynamic Connection Library
Global data in the Win32 dynamic connection library (DLL) can be shared by all the processes that call the DLL, which opens up a new way for inter-process communication, of course, pay attention to synchronization during access.
Although data can be shared between processes through DLL, we do not advocate this method from the perspective of data security. It is better to use shared memory with access control.

2.10 Remote Procedure Call
Remote Procedure Call (RPC) provided by Win32 API enables applications to call functions remotely, which makes Process Communication over RPC over the network as simple as function call.
RPC can be used between different processes on a single machine or in the network.
Since the RPC provided by Win32 API complies with the OSF-DCE (Open Software Foundation distributed computing environment) standard.
Therefore, RPC applications written using Win32 APIs can communicate with RPC applications that support Dec on other operating systems. RPC developers can establish high-performance, tightly coupled distributed application programming.

2.11 NetBIOS Functions
Win32 API provides NetBIOS functions for low-level network control, which is mainly used to compile interfaces with windows for the IBM NetBIOS system. Unless those applications have special low-level network functional requirements,
It is recommended that other applications do not use netbios functions for inter-process communication.

2.12 sockets
The Windows Sockets specification is a set of network programming interfaces in windows, which is defined in the example of popular socket interfaces in U. C. Berkeley University bsd unix. Except for the original library functions of Berkeley socket
And extended a set of functions for Windows, allowing programmers to make full use of the Windows messaging system for programming.
Currently, more and more network applications are using sockets to implement process communication. The main reason is that sockets is more cross-platform than other IPC Mechanisms. Besides, Winsock 2.0 not only supports TCP/IP protocol,
Other protocols (such as IPX) are also supported ). The only drawback of sockets is that it supports underlying communication operations, which makes it inconvenient to transmit simple data between standalone processes,
The following wm_copydata message is more suitable.

2.13 wm_copydata message
Wm_copydata is a very powerful but little-known message. When an application transmits data to another application, the sender only needs to call the sendmessage function,
The parameter is the window handle of the object, the start address of data transmission, and the message wm_copydata. The receiver only needs to process the wm_copy data message as it does other messages, so that the receiving and receiving sides can share data.
Wm_copydata is a very simple method, which is actually implemented through file ing at the underlying layer.

Its disadvantage is that it is not flexible and can only be used in a single-host Windows platform.

3 conclusion

Win32 API provides many options for applications to implement inter-process communication,
So how do Developers choose? The following questions should be considered before deciding which IPC method to use:
(1) Whether the application works in a network environment or a standalone environment.

Method 1: wm_copydata
Hwnd hreceivedatawindow = findwindow (null ,....)
Copydatastruct data;
Data. cbdata = strlen (pstr );
Data. lpdata = pstr;
Sendmessage (hreceivedatawindow, wm_copydata, (wparam) getfocus (), (lparam) & data );
Ref. The simplest way

Http://www.cppblog.com/TechLab/archive/2005/12/30/2272.aspx

Method 2: DLL sharing
# Pragma data_seg (". ashare ")
Int iwhatyouuseintwo = 0;
# Pragma data_seg ()

Method 3: image files
Ref. The most basic and efficient method
Best reference book windows core programming chapter 17th memory ing files

Http://blog.codingnow.com/2005/10/interprocess_communications.html


Method 4: anonymous pipe: createpipe
Method 5: Named Pipe: createnamedpipe
Ref.

Http://www.pediy.com/bbshtml/bbs8/pediy8-724.htm

Method 6: email Channel

Method 7: network interface, socket, But Nic required. Enable IPC between different hosts
Another well-summarized article

Http://www.seeitco.com/doc/Html/Visual%20C++/205637623.html

A process is usually defined as an instance of a running program. It consists of two parts:
One is the kernel object used by the operating system to manage processes. The kernel object is also used by the system to store process statistics.
The other is the address space, which contains the code and data of all executable modules or DLL modules. It also contains dynamically allocated space.
Such as thread stack and heap allocation space. Each process is assigned its own virtual address space. When a thread in the process is running, the thread can access the memory of the process that only belongs to it.
Memory of other processes is hidden and cannot be accessed by running threads.
In order to communicate between two processes, the following methods can be used for reference:

0. Clipboard clipboard: Commonly Used in the 16-bit era, supported by cwnd

1. The Windows message standard and the dedicated wm_copydata message sendmessage () receiver must have a window

2. Use shared memory (shared memory)
A. Set a shared memory area
Handle createfilemapping (handle, lpsecurity_attributes, DWORD, lpcstr)
Generate a file-mapping core object
Lpvoid mapviewoffile (
Handle hfilemappingobject,
DWORD dwdesiredacess,
DWORD dwfileoffsethigh,
DWORD dwfileoffsetlow,
DWORD dwnumberofbytestomap
);
Get the shared memory pointer
B. Find out the shared memory
It is determined that this memory should be presented in the form of peer to peer
Each process must have the same capability to generate shared memory and initialize it. Each process
Createfilemapping () should be called, and then getlasterror () should be called. If
The error code is error_already_exists, so the process can assume that the shared memory region has been opened and initialized by other processes. Otherwise, the process can reasonably think that it is ranked first, then, initialize the shared memory.
Still use the Client/Server Architecture
Only the server process should generate and initialize the shared memory. All processes should use

Handle openfilemapping (DWORD dwdesiredaccess,
Bool binherithandle,
Lptstr lpname );
Call mapviewoffile () to obtain the shared memory pointer.
C. synchronous processing (mutex)
D. Cleaning up bool unmapviewoffile (lpcvoid lpbaseaddress );
Closehandle ()

3. Dynamic Data Exchange (DDE) enables inter-application transfer by maintaining global memory allocation
The method is to manually place a large amount of data in the global memory, and then use the window message to pass the memory pointer. this is the method used in the 16-bit win era, because there is no global or local memory in Win32.
Now there is only one kind of memory, namely, virtual memory.

4. Message Pipeline)
This channel is used to set a permanent communication channel between applications.
Access a flat file to read and write data.
Anonymous pipeline (anonymous pipes)
One-way flow, and can only flow between processes on the same computer.
Named Pipes)
Two-way, cross-network, any process can easily grasp, the data put into the pipeline has a fixed format, and the use of readfile () can only read a multiple of this size.
Can be used in I/O Completion Ports

5. mailslots)
Broadcast Communication, a new method provided in 32 systems, supports data exchange between different hosts, and only supports mail slot customers in Win9x

6. Windows Socket)
It has all the functions of the message pipeline, but complies with a set of communication standards so that applications on different operating systems can communicate with each other.

7. Internet communication: allows an application to upload or download files from an Internet address.

8. RPC: Remote Procedure Call, rarely used, because it is not compatible with Unix RPC.

9. Serial/parallel communication (Serial/parallel communication)
It allows applications to communicate with other applications through serial or parallel ports.

10. COM/DCOM

& Nbsp; exchange data between processes through the proxy stubs of the com system, but only the interface

When calling a function, you can transmit data between different hosts through DCOM.

Related Article

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.