介绍
1、无名管道是linux系统下的一种ipc通信机制。
2、在linux下一切皆文件,管道也不列外,管道也是一种特殊的文件,在使用pipe()方法申请的时候,会得到两个文件描述符,一个用于写,一个用于读,这个特殊的“文件”,你可以理解为在系统的内存空间申请了一块地址专门用来进行读写。
作用
1、 主要用于进程间的通信,但是这里注意这里的进程是具有特殊关系的亲信进程,比如父进程和子进程、父进程和孙子进程、兄弟进程。
2、为什么只能亲信进程之间使用管道进行IPC通信呢?
原因是父进程使用pipe生成出文件描述符,之后父进程fork出的子进程是可以共享这个文件描述符进行操作的。非亲信的进程是拿不到这个文件描述符的。
用列
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
void read_data(int pipes[])
{
int c,rc;
close(pipes[1]);//读写之关掉写
while((rc = read(pipes[0], &c ,1)) > 0)
{
putchar(c);
}
exit(0);
}
void write_data(int pipes[])
{
int c ,rc;
close(pipes[0]);//写之前关掉读
while((c = getchar()) > 0)
{
rc = write(pipes[1], &c, 1);
if(rc == -1)
{
printf("write error\n");
close(pipes[1]);//关掉写
exit(1);
}
}
close(pipes[1]);//关掉写
exit(0);
}
int main() {
int pipefd[2]; //pipe[0]用于读,pipe[1]用于写
pid_t pid;
int rc = pipe(pipefd);
if (rc == -1) {
printf("pipes error\n");
exit(1);
}
pid = fork();
if (pid < 0) {
printf("fork error\n");
} else if (pid == 0) {
read_data(pipefd);
} else if (pid > 0) {
write_data(pipefd);
}
}
测试结果