Linux 进程的管道通信是一种进程间通信(IPC)的方式。
基础概念: 管道是一种半双工的通信方式,数据只能单向流动,而且只能在具有亲缘关系的进程间使用。进程的亲缘关系通常是指父子进程关系。
优势:
类型:
应用场景:
常见问题及原因:
示例代码(匿名管道):
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
int main() {
int pipefd[2];
pid_t pid;
char buffer[256];
if (pipe(pipefd) == -1) {
perror("pipe");
exit(EXIT_FAILURE);
}
pid = fork();
if (pid < 0) {
perror("fork");
exit(EXIT_FAILURE);
} else if (pid == 0) {
close(pipefd[1]); // 关闭写端
read(pipefd[0], buffer, sizeof(buffer));
printf("子进程收到数据:%s
", buffer);
close(pipefd[0]);
} else {
close(pipefd[0]); // 关闭读端
write(pipefd[1], "Hello from parent!", 18);
close(pipefd[1]);
}
return 0;
}
领取专属 10元无门槛券
手把手带您无忧上云