Each process has a different user address space, and the data exchange between processes must be done by opening up buffers in the kernel for data sharing.
Pipeline
Piping is the most basic IPC mechanism, created by the pipe function:
int pipe(int filedes[2]);
Call the pipe function in the kernel to open a buffer (called a pipe) for communication, it has a read end of a write end, and then passed through the Filedes parameter to the user program two file descriptor, Filedes[0] point to the read end of the pipe, filedes[1] point to the write end of the pipeline (very good remember, Just like 0 is standard input 1 is the same as standard output). So the pipeline in the user program looks like an open file, through Read (Filedes[0]), or write (filedes[1]); Reading and writing data to this file is actually reading and writing the kernel buffer.
A basic example is as follows:
#include <stdlib.h>#include <unistd.h>#define MAXLINE 80int 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;}
There are some limitations to using pipelines:
- The read-write side of the pipeline is passed through an open file descriptor, so the two processes to communicate must inherit the pipe file descriptor from their common ancestor.
- Two processes can only implement one-way communication through a single pipeline
Other IPC mechanisms
In addition to pipelines, there are several commonly used IPC mechanisms:
文件: 几个进程可以在文件系统中读写某个共享文件,也可以通过给文件加锁来实现进程间同步信号: 进程间使用SIGUSR1和SIGUSR2实现用户自定义功能Socket: 它还可以跨主机,并且标准统一,不同的操作系统都支持,是使用的最广泛的IPC机制内存映射:几个进程映射同一个内存区
From for notes (Wiz)
Linux advanced Programming--07. Interprocess communication