Android APK体积优化:别再让android:extractNativeLibs的默认值坑了你的安装速度
2026/6/5 3:48:56
进程空间独立,但进程间常需数据共享或交换,因此需要IPC机制。IPC允许不同进程高效协作,例如数据传输、同步操作等。IPC方式多样,可根据需求选择。
管道底层实现基于队列,支持高效数据传输。下面重点讨论无名管道和有名管道。
无名管道仅适用于有亲缘关系的进程(如父子进程)。它基于文件描述符操作,特性如下:
lseek)。open,read,write,close)或标准IO(带缓冲区)。int pipe(int pipefd[2]);pipefd[0]:固定读端。pipefd[1]:固定写端。示例使用:
#include <unistd.h> #include <stdio.h> int main() { int pipefd[2]; pid_t pid; if (pipe(pipefd) == -1) { perror("pipe error"); return -1; } pid = fork(); if (pid == 0) { // 子进程:写数据 close(pipefd[0]); // 关闭读端 write(pipefd[1], "Hello", 6); close(pipefd[1]); } else if (pid > 0) { // 父进程:读数据 close(pipefd[1]); // 关闭写端 char buf[10]; read(pipefd[0], buf, sizeof(buf)); printf("Received: %s\n", buf); close(pipefd[0]); } return 0; }有名管道(FIFO)适用于任意单机进程,在文件系统中可见(有路径名)。特性与无名管道一致,额外特性:
open函数会阻塞。int mkfifo(const char *pathname, mode_t mode);pathname:文件路径和名称。mode:八进制权限(如0666)。示例使用:
#include <sys/stat.h> #include <fcntl.h> #include <unistd.h> int main() { const char *fifo_path = "/tmp/myfifo"; // 创建有名管道 if (mkfifo(fifo_path, 0666) == -1) { perror("mkfifo error"); return -1; } // 进程A:写数据 int fd = open(fifo_path, O_WRONLY); write(fd, "Data from A", 12); close(fd); // 进程B:读数据 fd = open(fifo_path, O_RDONLY); char buf[20]; read(fd, buf, sizeof(buf)); close(fd); // 可选:卸载管道 unlink(fifo_path); return 0; }