notes/article/ipc/ipc.md

56 lines
1.7 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# 进程间通信
进程间通信IPCInterProcess Communication是指在不同进程之间传播或交换信息。
IPC的方式通常有管道包括无名管道和命名管道、消息队列、信号量、共享存储、Socket、Streams 等。
其中 Socket 和 Streams 支持不同主机上的两个进程IPC。
以Linux中的C语言编程为例。
## 管道
### 匿名管道
管道,通常指无名管道,是 UNIX 系统IPC最古老的形式。
特点:
1. 它是半双工的(即数据只能在一个方向上流动),具有固定的读端和写端。
2. 它只能用于具有亲缘关系的进程之间的通信(也是父子进程或者兄弟进程之间)。
3. 它可以看成是一种特殊的文件对于它的读写也可以使用普通的read、write 等函数。但是它不是普通的文件,并不属于其他任何文件系统,并且只存在于内存中。
```c
#include <unistd.h>
int pipe(int fd[2]); // 返回值若成功返回0失败返回-1
```
```plaintext
read write
+-------------------+
| fd[0] fd[1] |
+---^-----------+---+
| |
+---+-----------+------+
| | | |
| | +------+ | |
| +--+ pipe +<+ |
| +------+ |
| |
| kernel |
+----------------------+
```
### 命名管道
FIFO也称为命名管道它是一种文件类型。
特点:
1. FIFO可以在无关的进程之间交换数据与无名管道不同。
2. FIFO有路径名与之相关联它以一种特殊设备文件形式存在于文件系统中。
```c
#include <sys/stat.h>
// 返回值成功返回0出错返回-1
int mkfifo(const char *pathname, mode_t mode);
```