Talking about various communication modes between Windows process

Source: Internet
Author: User
Tags ole

1 Various methods for Windows interprocess 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. Microsoft WIN32 Application Programming Interface (application Programming Interface, API)
Provides a large number of mechanisms to support data sharing and exchange among applications that exercise activities called interprocess communication (interprocess communication, IPC),
Process communication refers to the data sharing and data exchange between different processes.
Because there are many ways of using the Win32 API for process communication, how to choose the proper communication mode becomes an important problem in application development.
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,
The contents of a file can be read and modified 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 a file,
Enables the sharing of data in a 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. But file mappings 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

Shared memory in the Win32 API is actually a special case of file mapping. The process uses 0xFFFFFFFF to replace the file handle (HANDLE) when creating a file-mapping object.

Indicates that the corresponding file-mapping object accesses memory from the operating system paging file, and other processes open the file-mapping object to access the memory block. Because shared memory is implemented with file mappings,
So it also has better security and can only run between processes on the same computer.

A. Setting a piece of shared memory area

HANDLE createfilemapping (Handle,lpsecurity_attributes, DWORD, DWORD, DWORD, LPCSTR)//Generate a file-mapping core object
LPVOID MapViewOfFile (
HANDLE Hfilemappingobject,
DWORD dwdesiredacess,
DWORD Dwfileoffsethigh,
DWORD Dwfileoffsetlow,
DWORD Dwnumberofbytestomap
); Get a pointer to shared memory

B. Find shared memory
The decision to render this memory in the form of peer to peer must have the same ability to generate shared memory and initialize it. Each process should call createfilemapping (),

Then call GetLastError (). If the error code returned is error_already_exists, then the process can assume that the shared memory area has been opened and initialized by another process.

Otherwise, the process can reasonably consider itself ranked first, and then the shared memory is initialized. Or to use the Client/server schema, only the server process should generate and initialize the shared memory.
All processes should use the
HANDLE openfilemapping (DWORD dwdesiredaccess,
BOOL bInheritHandle,
LPCTSTR lpname);
Call MapViewOfFile () again to get a pointer to the shared memory


C. Synchronous processing (Mutex)


D. Cleanup (cleaning up) BOOL unmapviewoffile (lpcvoid lpbaseaddress);

CloseHandle ()


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 and the other end is write-only;
It can also be a two-way pipeline where both ends of the point 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,

The channel's read endpoint handle or write endpoint handle is then inherited by the child process to communicate, and then the communication is implemented. 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.
When a 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 be given by the name of the mail slot
The message Slot server process sends a message. 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 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 cannot guarantee that the message will be received correctly once the network error occurs.
The Named pipes transmit data 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 mail slots are another option for applications 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 an intermediary for data sharing between Windows applications.
Windows has established a cut (copy)-paste mechanism that provides a quick way to share different formats of 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 loose exchange medium that can support any data format, each format is identified by an unsigned integer, and the standard (pre-defined) Clipboard format, which is a constant defined by the Win32 API;
For non-standard formats, you can register the new clipboard format with the Register Clipboard format function. Data exchanged using the Clipboard can only be consistent in the data format or
Convert to a certain format on the line. 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 when new data appears,
Dynamically exchange data between applications by sending update values.
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 transmission mechanism is different, one obvious difference is that the clipboard operation almost
Always serves as a one-time answer to a user-specified action-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 documentation. 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. Except for applications that have special low-level network functionality requirements,
Other applications are best not to 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
, it also extends a set of functions for windows that allow 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 TCP/IP protocol, but also
Other protocols, such as IPX, are also supported. The only drawback of sockets is that it supports the underlying communication operations, which makes simple data transfer between single-machine processes less convenient,
It would be more appropriate to use the WM_COPYDATA message described below.

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,
The parameter 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 the application to implement interprocess communication,
So how do developers make a 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.

Method One: 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 Two: DLL sharing
#pragma data_seg (". Ashare ")
int iwhatyouuseintwo = 0;
#pragma data_seg ()


Method Three: Image file
REF. The most basic and efficient method
The best reference book, "Windows Core Programming", chapter 17th, memory-mapped files
Http://blog.codingnow.com/2005/10/interprocess_communications.html

Method Four: Anonymous pipe: CreatePipe
Method Five: Named pipes: CreateNamedPipe
REF.
Http://www.pediy.com/bbshtml/bbs8/pediy8-724.htm

Method Six: Mail channel

Method Seven: Network interface, socket, but requires a network card. Can implement IPC between different hosts
Another summary of the relatively good article
Http://www.seeitco.com/doc/Html/Visual%20C++/205637623.html


A process is typically defined as an instance of a running program that consists of two parts:
One is the kernel object that the operating system uses to manage processes. The kernel object is also the place where the system holds statistical information about the process.
The other is the address space, which contains all the code and data for the executable module or DLL module. It also contains dynamically allocated space.
such as thread stacks and heap allocation space. Each process is given its own virtual address space, and when a thread in the process is running, the thread can access the memory of only the processes that belong to it.
Memory belonging to other processes is hidden and cannot be accessed by a running thread.
In order to be able to communicate between two processes, the following methods are available for reference:

0. Clipboard clipboard: In the 16-bit era often used in the way, CWnd provides support

1. window messages standard Windows messages and dedicated Wm_copydata messages SENDMESSAGE () receive end must have a window

2. Use shared memory mode
A. Setting a piece of shared memory area
HANDLE createfilemapping (Handle,lpsecurity_attributes, DWORD, DWORD, DWORD, LPCSTR)
Produce a file-mapping core object
LPVOID MapViewOfFile (
HANDLE Hfilemappingobject,
DWORD dwdesiredacess,
DWORD Dwfileoffsethigh,
DWORD Dwfileoffsetlow,
DWORD Dwnumberofbytestomap
);
Get pointers to shared memory
B. Find shared memory
Determine if this memory is to be presented in the form of point-to-point (peer to peer)
Each process must have the same ability to generate shared memory and initialize it. Each process
should call CreateFileMapping () and then call GetLastError (). If the returned
The error code is error_already_exists, so the process can assume that the shared memory area has been opened and initialized by another process, otherwise the process can reasonably consider itself ranked first, and then the shared memory will be initialized.
Or do you want to use the Client/server schema
Only the server process should generate and initialize shared memory. All processes should use the

HANDLE openfilemapping (DWORD dwdesiredaccess,
BOOL bInheritHandle,
LPCTSTR lpname);
Call MapViewOfFile () again to get a pointer to the shared memory
C. Synchronous processing (Mutex)
D. Cleanup (cleaning up) BOOL unmapviewoffile (lpcvoid lpbaseaddress);
CloseHandle ()

3. Dynamic Data Exchange (DDE) makes it possible to transfer between applications by maintaining a globally allocated memory
This is done by manually placing large amounts of data in a piece of global memory, and then passing the memory pointer using a window message. This is the way to use the 16-bit win era, because there is no global and local memory under WIN32
, now only one of the memory is virtual storage.

4. Message pipeline (Messages pipe)
Used to set up a permanent communication channel between applications, through which the channel can be like its own application
Access to a flat file as well as read and write data.
Anonymous pipeline (Anonymous Pipes)
One-way flow and can only flow between processes on the same computer.
Named Pipes (Named Pipes)
Bidirectional, across the network, any process can be easily grasped, the data placed into the pipeline has a fixed format, while using ReadFile () can only read multiples of that size.
Can be used for I/O completion Ports

5 Mail Slots (mailslots)
Broadcast communication, the new method provided in the 32 system, can exchange data between different hosts, only support mail slot customers under Win9x

6. Windows Sockets (Windows socket)
It has all the functionality of the message pipeline, but adheres to a set of communication standards so that applications on different operating systems can communicate with each other.

7. Internet communication it lets applications upload or download files from an Internet address

8. RPC: Remote procedure call, rarely used because it is incompatible with RPC for UNIX.

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

10. Com/dcom

Inter-process data exchange through the proxy stub of COM systems, but only in the interface

function, the data can be transferred between different hosts through DCOM.

Talking about various communication modes between Windows process

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.