管道
什么是管道
管道本质还是文件,是一种比较特殊的文件
管道的分类与作用
有名管道和无名管道
有名管道:主要由程序员手动创建,实现任意两个进程间的通信
无名管道:主要由系统创建,用于父子进程之间的通信
使用
有名管道
终端间通信
终端A:
[terminal]
moyu@ubuntu:~/Code/pipe$mkfifo a.pipe
moyu@ubuntu:~/Code/pipe$ echo "hello">>a.pipe
终端B:
[terminal]
moyu@ubuntu:~/Code/pipe$ cat a.pipe
hello
进程间的通信
有名管道的操控就是操控文件,如同文件一般打开写入即可。
终端A:
[terminal]
moyu@ubuntu:~/Code/pipe$ vim fifo_pipe_write.c
fifo_pipe_write.c
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
int main(void)
{
//1.打开文件
int fd=open("fifo.pipe",O_WRONLY|O_CREAT|O_TRUNC,0644);
if(-1==fd)
{
perror("open"),exit(-1);
}
//2.发送数据
int i=0;
for(i=0;i<100;i++)
{
write(fd,&i,sizeof(int));
usleep(100000); //0.1秒
}
//3.关闭文件
close(fd);
return 0;
}
终端B:
fifo_pipe_read.c
//使用有名管道实现进程间的通信
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
int main(void)
{
//1.打开文件
int fd=open("fifo.pipe",O_RDONLY);
if(-1==fd)
{
perror("open"),exit(-1);
}
//2.接受数据
int i=0;
for(i=0;i<100;i++)
{
int x=0;
read(fd,&x,sizeof(int));
printf("%d ",x);
//刷新输出缓冲区
fflush(stdout);
}
printf("\n");
//3.关闭文件
close(fd);
return 0;
}
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99
无名管道
函数
#include<unistd.h>int pipe(int pipefd[2]);
函数功能:主要用于创建一个无名管道,作为进程间通信的数据通道
参数带出两个文件描述符,其中pipefd[0]代表读端;pipefd[1]代表写端.
返回值:成功返回0,失败返回-1.
匿名管道用于父子进程的使用所以要创建子进程。
//使用无名管道实现父子进程之间的通信
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
int main(void)
{
//1.创建无名管道
int pipefd[2]={0};
int res=pipe(pipefd);
//创建无名管道失败
if(-1==res)
{
perror("pipe"),exit(-1);
}
//2.创建子进程
pid_t pid=fork();
// 子进程创建失败
if(-1==pid)
{
perror("pipe"),exit(-1);
}
//3.子进程读取数据
if(0==pid)
{
//关闭写端
close(pipefd[1]);
int i=0;
for(i=0;i<100;i++)
{
int x=0;
//在读端读取无名管道的数据
read(pipefd[0],&x,sizeof(int));
printf("%d ",x);
//刷新缓存
fflush(stdout);
}
printf("\n");
//关闭读端
close(pipefd[0]);
//终止子进程
exit(0);
}
//4.父进程写入数据
//关闭读端
close(pipefd[0]);
int i=0;
for(i=0;i<100;i++)
{
write(pipefd[1],&i,sizeof(int));
usleep(100000); //睡眠0.1秒
}
//关闭写端
close(pipefd[1]);
return 0;
}
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99