linux无名管道通信特点
- 无名管道是半双工的通信方式,数据只能一方发送,另一方接收。
- 无名管道只适用于亲缘关系的进程通信。
- 数据的读出和写入:一个进程向管道中写的内容被管道另一端的进程读出。写入的内容每次都添加在管道缓冲区的末尾,并且每次都是从缓冲区的头部读出数据。
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
void read_data(int *);
void write_data(int *);
int main()
{
int pipefd[2];
pid_t cpid;
char buf;
if (pipe(pipefd) == -1)
{
perror("pipe");
exit(1);
}
cpid=fork();
switch(cpid)
{
case -1:
perror("creat proess failed");
exit(1);
case 0:
read_data(pipefd);
default:
write_data(pipefd);
}
return 0;
}
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<0)
{
perror("write file error");
close(pipes[1]);
exit(1);
}
}
close(pipes[1]);
exit(0);
}
- 主函数说明:主函数中使用pipe()函数创建无名管道,此时返回值为二维句柄,存入pipefd[2]中,其中pipefd[0]为无名管道读句柄,pipefd[1]为无名管道写句柄
- 读函数:首先关闭写,再使用系统函数read从管道中读取字符就可以了
- 写函数:首先关闭读,再使用系统函数write向管道中写字符就可以了