在 Ubuntu(Linux)环境下,进程间通信(IPC,Inter-Process Communication)有多种实现方式,下面按常用程度和使用场景给你系统梳理一下。
特点
示例(C)
int fd[2];
pipe(fd);
if (fork() == 0) {
// 子进程
close(fd[1]);
read(fd[0], buf, sizeof(buf));
} else {
// 父进程
close(fd[0]);
write(fd[1], "hello", 5);
}
Shell 中
ls | grep test
特点
创建
mkfifo /tmp/myfifo
写进程
echo "hello" > /tmp/myfifo
读进程
cat /tmp/myfifo
特点
API
msggetmsgsndmsgrcv步骤
示例(POSIX)
shm_open("/myshm", O_CREAT | O_RDWR, 0666);
mmap(...)
⚠️ 通常需要配合 信号量 做同步
示例
kill(pid, SIGUSR1);
常用信号
类型
Unix Socket 示例
socket(AF_UNIX, SOCK_STREAM, 0);
bind();
listen();
accept();
Python 示例
import socket
s = socket.socket(socket.AF_UNIX)
s.connect("/tmp/test.sock")
dbus-send ...
| 场景 | 推荐方式 |
|---|---|
| 父子进程 | pipe |
| 本地多进程 | 共享内存 + 信号量 |
| 稳定服务通信 | Unix Socket |
| 桌面程序 | D-Bus |
| 简单通知 | Signal |
| 高性能 | 共享内存 |
我可以:
你现在的场景是?
(比如:两个 Python 程序?C 服务?Ubuntu 后台进程?)