定义:
内核提供:单工 (一端写端 一端读端) 自同步机制(写端写满后会阻塞等待,直到等到读端读取数据后,写端才会再写入数据)
1.匿名管道:进程间有亲缘关系使用(无法在磁盘看到)
创建方法:pipe()函数 int pipe(int pipefd[2]);
fd[0]:读端 fd[1]:写端
2.命名管道:进程间无亲缘关系使用(可以在磁盘看到 格式为p)
创建方法: mkfifo函数 int mkfifo(const char *pathname, mode_t mode);
参数1.名字 参数2.权限
命名管道使用:
终端1 创建管道 并将当前日期输入管道
终端2 读取管道内容
匿名管道使用
//匿名管道使用:
#include<stdlib.h>
#include<unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#define BUFSIZE 1024
int main()
{
char buf[BUFSIZE];
int pd[2];//读写端数组
if(pipe(pd)<0)
{
perror("pipe()");
exit(1);
}
pid_t pid=fork();
if(pid<0)
{
perror("pid()");
exit(1);
}
if(pid==0)//子进程 read
{
close(pd[1]);//关闭写端
int len=read(pd[0],buf,BUFSIZE);//读取读端
write(1,buf,len);//写入终端
close(pd[0]);
exit(0);
}
else//父进程 write
{
close(pd[0]);//关闭读端
write(pd[1],"hello!",6);//向管道写端写内容
close(pd[1]);
wait(NULL);//回收子进程
exit(0);
}
return 0;
}
//使用匿名管道实现数据的下载 并解码(伪码)
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
int main()
{
char buf[BUFSIZE];
int pd[2];//读写端数组
if(pipe(pd)<0)
{
perror("pipe()");
exit(1);
}
pid_t pid=fork();
if(pid<0)
{
perror("pid()");
exit(1);
}
if(pid==0)//子进程 read
{
close(pd[1]);//关闭写端
dup2(pd[0],0);//读端重定向标准输出 第一个参数old fd 第二个参数new fd
close(pd[0]);//关闭读端
int fd=open("/dev/null",O_RDWR);
dup2(fd,1);
dup2(fd,2);
execl("/usr/bin/mpg123","mpg123","-",NULL);//当前子进程变为mpg123 成为解码器
perror("error");
exit(1);
}
else//父进程 write
{
close(pd[0]);//关闭读端
//write(pd[1],"hello!",6);//向管道写端写内容
//父进程从网上收数据 往管道中写
close(pd[1]);
wait(NULL);//回收子进程
exit(0);
}
return 0;
}