一、简介
从 UNIX 系统开始,无名管道的通信方式就存在,有点类似硬件中的串口,从最初的设计
者定型之后,这种模型就一直延续到今天,说明无名管道当初设计的就极具科学性。不过无名管道有一定的局限性。
第一:它是属于半双工的通信方式;
第二:只有具有“亲缘关系”的的进程才能使用这种通信方式,也就是父进程和子进程之
间。
接着介绍一下 pipe 函数。
int pipe(int pipefd[2])
参数 pipefd[0]:用于读管道。
参数 pipefd[1]:用于写管道。
返回值:执行成功返回 0,失败返回-1。
二、操作过程
在PC机上操作
1.root@ubuntu:/home/jin# arm-none-linux-gnueabi-gcc -o pipe pipe.c -static
2.root@ubuntu:/home/jin# cp pipe /var/tftpboot/
在开发板上操作
3.[root@iTOP-4412]# tftp -g -l pipe -r pipe 192.168.0.12
4.[root@iTOP-4412]# chmod +x pipe
5.[root@iTOP-4412]# ./pipe
三、实例程序
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>
//进程读函数
void read_data(int *);
//进程写函数
void write_data(int *);
int main(int argc,char *argv[])
{
int pipes[2],rc;
pid_t pid;
rc = pipe(pipes); //创建管道
if(rc == -1){
perror("\npipes\n");
exit(1);
}
pid = fork(); //创建进程
switch(pid){
case -1:
perror("\nfork\n");
exit(1);
case 0:
read_data(pipes); //相同的pipes
default:
write_data(pipes); //相同的pipes
}
return 0;
}
//进程读函数
void read_data(int pipes[])
{
int c,rc;
//由于此函数只负责读,因此将写描述关闭(资源宝贵)
close(pipes[1]);
//阻塞,等待从管道读取数据
//int 转为 unsiged char 输出到终端
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 ){
perror("Parent: write");
close(pipes[1]);
exit(1);
}
}
close( pipes[1] );
exit(0);
}