无名管道
从最早的UNIX 系统开始,无名管道的通信方式就存在,有点类似硬件中的串口,从最初的设计者定型之后,这种通信模型就一直延续到今天,说明无名管道当初的设计就极具科学性。
管道是单独构成一种独立的文件系统:管道对于管道两端的进程而言,就是一个文件,但它不是普通的文件,它不属于某种文件系统,而是自立门户,单独构成一种文件系统,并且只存在与内存中。数据的读出和写入:一个进程向管道中写的内容被管道另一端的进程读出。写入的内容每次都添加在管道缓冲区的末尾,并且每次都是从缓冲区的头部读出数据。
无名管道有一定的局限性。
第一:它是属于半双工的通信方式;
第二:只有具有“亲缘关系”的的进程才能使用这种通信方式,也就是父进程和子进程之间。
pipe 函数
int pipe(int pipefd[2])
参数 pipefd[0]:用于读管道。
参数 pipefd[1]:用于写管道。
返回值:执行成功返回 0,失败返回-1。
无名管道例程
#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 rc;
char c[100],d[]= {'e','x','i','t'}; //定义程序结束码d[]
//关闭读描述字
close(pipes[0]);
while((c=gets()) > 0 ){
if(strcmp(c,d) == 0) //程序出口
{
printf("\nFunction will exit\n");
exit(1);
}
rc = write( pipes[1], &c, 1); //写入管道
if( rc == -1 ){
perror("Parent: write");
close(pipes[1]);
exit(1);
}
}
close( pipes[1] );
exit(0);
}