进程间通信——管道通信

定义:
内核提供:单工 (一端写端 一端读端) 自同步机制(写端写满后会阻塞等待,直到等到读端读取数据后,写端才会再写入数据)
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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值