Each process has a different user address space. to exchange data between processes, you must open a buffer in the kernel to achieve data sharing.
MPs queue
Pipelines are the most basic IPC mechanism created by the pipe function:
Int pipe (int filedes [2]);
When the pipe function is called, a buffer (called pipeline) is opened in the kernel for communication. It has a read end and a write end, and then transmitted to the user program through the filedes parameter, filedes [0] points to the read end of the pipeline, and filedes [1] points to the write end of the pipeline (it is easy to remember, just as 0 is the standard input 1 is the standard output ). Therefore, the pipeline looks like an open file in the user program, through read (filedes [0]); or write (filedes [1]); reading and writing data to this file is actually a read and write kernel buffer.
A basic example is as follows:
# Include <stdlib. h>
# Include
<Unistd. h>
# Define MAXLINE 80
Int main (void)
{
Int n;
Int fd [2];
Pid_t pid;
Char line [MAXLINE];
If (pipe (fd) <0 ){
Perror ("pipe ");
Exit (1 );
}
If (pid = fork () <0 ){
Perror ("fork ");
Exit (1 );
}
If (pid> 0) {/* parent */
Close (fd [0]);
Write (fd [1], "hello world \ n", 12 );
Wait (NULL );
} Else {/* child */
Close (fd [1]);
N = read (fd [0], line, MAXLINE );
Write (STDOUT_FILENO, line, n );
}
Return 0;
}
MPs queue has some restrictions:
- The read and write ends of the MPs queue are passed through the opened file descriptor. Therefore, the two processes to communicate must inherit the file descriptor of the MPs queue from their common ancestor.
- Two processes can only achieve one-way communication through one pipe
Other IPC Mechanisms
In addition to pipelines, there are also several commonly used IPC Mechanisms:
- File: several processes can read and write a shared file in the file system, or they can implement inter-process synchronization by locking the file.
- Signal: Use SIGUSR1 and SIGUSR2 between processes to implement User-Defined Functions
- Socket: it can also be cross-host and standardized. It is supported by different operating systems and is the most widely used IPC Mechanism.
- Memory ing: several processes map to the same memory zone.