Windows Process Communication Methods

Source: Internet
Author: User
The process is loaded into the memory and ready for execution.Program, Each process has a private virtual address spaceCode, Data and the system resources it can use ( Such as files and Pipelines ) . Multi-Process / Multithreading is Windows A basic feature of the operating system. Microsoft Win32 Application Programming Interface (Application Programming Interface, API) Provides a large number of mechanisms to support data sharing and exchange between applications. These mechanisms are called inter-process communication. (Interprocess communication, IPC) Process communication refers to data sharing and data exchange between different processes.
This is because Win32 API There are many process communication methods. How to select an appropriate communication method becomes an important issue in application development. Win32 Process Communication methods are analyzed and compared.

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, and can read and modify the file content with simple pointer operations.
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 the file.
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. 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 handle, which means that the corresponding file ing object accesses the memory from the file on the operating system page, other processes can open the file ing object to access the memory block. Because shared memory is implemented by file ing, it also has good 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. Each process should call createfilemapping () and then 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 other processes, 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 one-way-one end is read-only, and the other end point is write-only. It can also be two-way. The two ends of a pipeline are 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 parent process creates a channel, and then the child process to communicate inherits the channel's read endpoint handle or write endpoint handle, 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 an anonymous pipe, a named pipe can be used between unrelated processes and between different computers. When the server creates a named pipe, a name is specified for it, any process can use this name to open the other end of the pipeline 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 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. Therefore, multiple mail slots can be established 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, while 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 pasting Mechanism provides a shortcut for different applications to share data of different formats. When a user performs a cut or copy operation in an application, the user should place the selected data on the clipboard in one or more formats. 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 it as the new clipboard format. You only need to use the clipboard to exchange data in the same format or convert the data 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 dynamically exchange data between applications by sending update values when new data appears.
Like clipboard, DDE supports both standard data formats (such as text and bitmap) and custom data formats. However, their data transmission mechanisms are different. One obvious difference is that clipboard operations are almost always used as a one-time response to user-specified operations-for example, selecting 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, the table is updated in the original word processor document. 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 there are applications with special low-level network functional requirements, it is recommended that other applications do not use the NetBIOS function 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. In addition to the original library functions of Berkeley socket, a group of functions for windows are also extended, so that programmers can 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. In this case, the wm_copydata message described below will be 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 parameters are the handle of the destination window, the start address of the data transmission, and the wm_copydata message. 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. How can 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 to 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, the most efficient method the best reference book windows core programming chapter 17th memory ing file 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 summary is better. 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,
lpctstr lpname);
call mapviewoffile (), 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, and currently there is only one kind of memory: 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
Data is exchanged between processes through the proxy stubs of the com system, but data can only be transferred when calling interface functions, and data can be transferred between different hosts through DCOM.

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.