Several methods of inter-process communication

Source: Internet
Author: User
Tags readfile

Programmers must coordinate the process set with dependency to achieve the common goal of the process. Two techniques can be used for coordination. The first technique transmits information between two processes with communication dependencies. This technology is called interprocess communication ). The second technology is synchronization, which is used when processes are mutually dependent on each other. The two types of dependency can exist at the same time.

Generally, a process has a separate address space. We can understand a series of mappings established after the executable program is loaded into the memory. This means that if we have two processes (process a and process B), the data declared in process a is unavailable to process B. In addition, process B cannot see the events in process A, and vice versa. If process a and process B work together to complete a task, there must be a method for communication information and time between two processes. Here we can look at the basic process components. Note that a process has a piece of text, data, and stack. The process may also have other memory allocated from the free storage space. The data occupied by a process is generally stored in data fragments, stack fragments, or dynamic memory allocated by the process. Data is protected by other processes. To allow a process to access the data of another process, it must be called by the operating system. Similarly, a communication mode must be established between processes to let a process know the events that occur in the text fragments of another process. This also requires help from the operating system API. When a process sends data to another process, it is called interprocess communication ). The following lists several different types of inter-process communication methods:

 

Description of inter-process communication

The environment variable/file descriptor sub-process accepts the copy of the Environment Data of the parent process and all file descriptors. A parent process can set certain variables in its data fragments or environment, and the child process receives these values. The parent process can open the file and push forward the read/write pointer position, and the child process uses the same offset to access the file.

 

Command line parameters can be passed to sub-processes when exec or derived functions are called.

 

A media transcoding queue is used to communicate with unrelated processes and form a communication channel between two processes. It is usually accessed by a file read/write program.

 

Shared Memory is a memory block other than two processes. Both processes can access it.

 

DDE (Dynamic Data Exchange, using the client/server model (C/S), server-to-Customer Data

Dynamic Data Exchange) or action requests to respond.

 

I. environment variables and file descriptors:

When a child process is created, it accepts copies of many resources of the parent process. The sub-process accepts the text and stack of the parent process.

And copy of data fragments. The child process also accepts the environment data of the parent process and copies of all file descriptors. Subentry

The process of inheriting resources from the parent process creates an opportunity for inter-process communication. The parent process can be in its data fragment or loop.

And the sub-process accepts these values. Similarly, the parent process can open a file and push it

The desired location in the file. Then, the child process can access the file at the exact location where the parent process leaves the read/write pointer.

 

The defect of such communication lies in its unidirectional and one-time communication. That is to say, apart from the file description, if the sub-process

It inherits any other data and only all the data copied by the parent process. Once a child process is created

Any changes to these variables are not reflected in the data of the parent process. Similarly, after a child process is created

Any changes will not be reflected in the sub-process. Therefore, this type of inter-process communication is more like baton transmission. Once parent

The sub-process is independent of some resources and must use the original transfer resource.

 

Ii. command line parameters:

You can use the command-line argument to complete one-way and one-time inter-process communication.

I have mentioned the use of command line parameters in the previous article. The command line parameter is used to call an exec or derived call operation.

To the sub-process. A command line parameter is usually passed to Exec As a null termination string in one of the parameters.

Or call a derived function. These functions can pass values to sub-processes in one-way and one-time mode. Windows has a call to execute

The API of the EXE program. You can refer to the shellexecutea function.

 

3. Pipeline communication:

Inheriting resources and command line parameters is the simplest form of inter-process communication. They have two main restrictions at the same time. Except for files

In addition to descriptors, the inherited resources are in the one-way and one-time form of IPC. Passing command parameters is also a one-way, one-time IPC

Method. These methods are only restricted to associated processes. If they are not associated, command line parameters and inherited resources cannot be used. Also

There is another structure called pipe, which can be used for communication between associated processes and between non-associated processes.

A pipe is a data structure that is accessed like a serialized file. It forms a communication channel between two processes.

The pipeline structure is accessed by using text and write methods. If process a wants to send data to process B through a pipeline

Process a writes data to the MPs queue. In order for process B to receive this data, process B must read the MPs queue and

The IPC format is different. The MPs queue supports two-way communication. The data flow between two processes is two-way communication. Pipelines can be stored in

Used throughout the execution, sending and receiving data between processes. Therefore, an MPS queue acts as a process between accessible MPs queues.

There are two basic MPs queue types:

1. Anonymous Pipeline

2. Named Pipe

 

The figure above shows that the two processes cannot write to each other without pipelines.

 

After creating an MPS queue, you can communicate with each other.

Only associated processes can use anonymous pipelines for communication. A named pipe must be used for a non-associated process.

Anonymous pipeline: provides access to anonymous pipelines through file descriptors or file handles. Create an MPS queue for system API calls and return a file descriptor. This file descriptor is used as a parameter for the read () or write () functions. When you call read () or write () through a file descriptor, the source and target of the data are pipelines. For example, in the OS/2 environment, use the operating system function doscreatepipe () to create an anonymous pipeline:

Int Mian (void)

{

Pfhile readhandle;

Pfhile writehandle;

Doscreatepipe (readhandle, writehandle, size );

...

...

...

}

In Windows, for example, the following code block in the ASM integration environment that I wrote that communicates with the doscommand line through the pipeline:

Void cidemanager: commond (cstring cmd, char * Buf, unsigned int bufsize)

{

Security_attributes SA;

Handle hread, hwrite;

SA. nlength = sizeof (security_attributes );

SA. lpsecuritydescriptor = NULL;

SA. binherithandle = true;

 

If (! Createpipe (& hread, & hwrite, & SA, 0) // create an MPS queue

{

Return;

}

 

Startupinfo Si;

Process_information PI;

Si. cb = sizeof (startupinfo );

Getstartupinfo (& Si );

Si. hstderror = hwrite;

Si. hstdoutput = hwrite;

Si. wshowwindow = sw_hide;

Si. dwflags = startf_useshowwindow | startf_usestdhandles;

 

If (! CreateProcess (null, (lptstr) (lpctstr) cmd, null, null, true, null, null, & Si, & PI ))

{

Return;

}

 

Closehandle (hwrite );

 

DWORD bytesread;

While (true)

{

Memset (BUF, 0, bufsize );

If (readfile (hread, Buf, bufsize, & bytesread, null )! = NULL)

{

Break;

}

Sleep (200 );

}

Closehandle (hread );

Return;

}

 

Named Pipe: uses a pipe as the communication channel between two unrelated processes. programmers must use a named pipe, which can be considered as a special type of file with a name. A process can access this pipeline according to its name. Through the anonymous pipeline, the Parent and Child processes can use file descriptors to access the channel they share, because the child process inherits the file descriptor of the parent process and the file descriptor is read () or write () function parameters. Because unrelated processes cannot access each other's file descriptors, they cannot use anonymous pipelines. Since the named pipe provides an equivalent file name for the pipe, any process that knows the name of the pipe can access it. The advantages of named MPs queue over anonymous MPs queue are as follows:

Named MPs queues can be used by non-associated processes.

The named pipe can be persistent. After the program is created and exited, they can still exist.

Named MPs queues can be used in networks or distributed environments.

Named pipelines are easy to use in many-to-one relationships.

Like accessing anonymous pipelines, named pipelines are also accessed through the read () or write () functions. The main difference between the two lies in the creation method of the named pipeline and who can ask them. A named pipe can establish a C/S model for inter-process communication. The processes that access the named MPs queue may all be on the same machine or different machines that communicate over the network. Because the pipeline name can be accessed through the logic name of the server where the pipeline is located, the pipeline can be accessed across networks. For example, //// servername // pipe // mypipe (case-insensitive) can be used as a pipe name. Assume that server1 is the name of the network server. When you open or access the call resolution file name of this pipeline, you should first locate server1 and then access mypipe. Example:

 

Server:

Int main (void)

{

Handle pipehandle;

Char Buf [256];

DWORD bytesread;

 

If (pipehandle = createnamedpipe ("////. // pipe // Cao ", pipe_access_duplex, pipe_type_byte | pipe_readmode_byte, 1, 0, 0, 5000, null) = invalid_handle_value)

{

Printf ("createnamedpipe failed with error % d/N", getlasterror ());

System ("pause ");

Return 0;

}

 

Printf ("server is running/N ");

If (connectnamedpipe (pipehandle, null) = 0)

 

{

Printf ("connectnamedpipe failed with error % d/N", getlasterror ());

Closehandle (pipehandle );

System ("pause ");

Return 0;

}

 

If (readfile (pipehandle, Buf, sizeof (BUF), & bytesread, null) = 0)

 

{

Printf ("readfile failed with error % d/N", getlasterror ());

Closehandle (pipehandle );

System ("pause ");

Return 0;

}

 

Printf ("% s/n", Buf );

If (disconnectnamedpipe (pipehandle) = 0)

 

{

Printf ("disconnectnamedpipe failed with error % d/N", getlasterror ());

Closehandle (pipehandle );

System ("pause ");

Return 0;

}

 

System ("pause ");

Return 0;

}

 

 

Client:

Int main (void)

{

Handle pipehandle;

DWORD writesbytes;

Char buff [256];

 

If (waitnamedpipe ("//. // pipe // Cao", nmpwait_wait_forever) = 0)

{

Printf ("waitnamedpipe failed with error % d/N", getlasterror ());

System ("pause ");

Return 0;

}

 

If (pipehandle = createfile ("////. // pipe // Cao ", generic_read | generic_write, 0, (lpsecurity_attributes) null, open_existing, file_attribute_normal, (handle) null) = invalid_handle_value)

{

Printf ("createfile failed with error % d/N", getlasterror ());

System ("pause ");

Return 0;

}

 

Zeromemory (& buff, sizeof (buff ));

Gets (buff );

 

If (writefile (pipehandle, buff, sizeof (buff), & writesbytes, null) = 0)

{

Printf ("writefile failed with error % d/N", getlasterror ());

Closehandle (pipehandle );

System ("pause ");

Return 0;

}

Printf ("write % d bytes", writesbytes );

Closehandle (pipehandle );

 

System ("pause ");

Return 0;

}

 

A named pipe can be used not only for communication between non-associated processes and two processes located on different machines, but also for multi-to-one communication and server processes, allow multiple users to access the named pipe at the same time. Named pipelines are often used for multi-threaded servers.

We have mentioned several methods, but also the following methods to implement inter-process communication:

Iv. Shared Memory

Shared Memory can also implement inter-process communication. Memory blocks that can be browsed by other processes. Other processes that want to access this memory block request access to it, or the process that creates it grants the access permission to the memory block. All processes that can access a specific memory block have immediate visibility into it. The shared memory is mapped to the address space of each process that uses it. So it looks like another variable declared in the process. When a process writes shared memory, all processes immediately know the written content and can access it.

The relationship between shared memory between processes is similar to the relationship between global variables between functions. All functions in the program can use the value of global variables. Similarly, shared memory blocks can be accessed by all processes in progress. A memory block may share a logical address, and a process may also share some physical addresses.

The creation of shared memory blocks must be completed by a system API call. In the Win32 environment, the createfilemapping (), mapviewoffile (), and mapviewoffileex () APIs can be used well.

The shared memory is allocated in the Win32 system ~ Within the 3 GB address range. Once mapviewoffile () and mapviewoffileex () are called, all processes of the shared file ing object can access this memory block immediately and read and write this memory block as needed.

5. Dynamic Data Exchange

Dynamic Data Exchange is one of the most powerful and complete forms of inter-process communication. Dynamic Data Exchange uses message transmission, shared memory, transaction protocol, customer/Server category, synchronization rules, and Session Protocol to allow data and control information to flow between processes. The basic model of Dynamic Data Exchange SESSION (DDE) is the customer and server. The server responds to data or actions from customers. Customers and servers can communicate with each other in multiple ways.

A server can communicate with any number of customers. A customer can also communicate with any number of servers. A single DDE proxy can be either a customer or a server. That is to say, a process can request a service from a DDE proxy that is executing services for another process.

 

This article from the csdn blog, reproduced please indicate the source: http://blog.csdn.net/masefee/archive/2009/05/13/4177196.aspx

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.