linux:13进程间的通信—管道

管道的分类:

  • 有名管道:(在磁盘上会存在一个管道文件标识,但是管道文件不占用磁盘block空间,数据会缓存在内存上),任意两个进程之间都可以
  • 无名管道:父子进程之间使用。

有名管道下

打开方式只有两种,一种是只读,一种是只写方式**

//创建一个管道文件:mkfifo  fifo
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <assert.h>
#include <fcntl.h>

int main()
{
//只写方式
int fd = open("filo",O_WRONLY);
assert( fd = -1);

while(1)
{
char buff[128] = {0};
printf("input:\n");
//读取文件
fgets(buff,128,stdin);
if(strcmp(buff,"end",3) == 0)
{
break;
}
write(fd,buff,strlen(buff));
}
//关闭文件
close(fd);
exit(0); 
}

只写方式:

int main()
{
int fd = open("filo",O_RDONLY);
assert( fd = -1);
while(1)
{
char buff[128] = {0};
int n = read(fd,buff,127);
if( n==0 )
{
break;
}
printf("read:%s\n,buff");
}
//关闭文件
close(fd);
exit(0); 
}

注:open有同步,需要一读一写才能打开,若管道为空,读会阻塞。管道写端关闭,读,read返回值为零。

无名管道:

1.pipe()创建无名管道

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <assert.h>
#include <fcntl.h>

int main()
{
//创建一个无名管道
//定义一个数组
int fd[2];//fd[0] 只读,  fd[1] 只写
assert(pipe(fd)  != -1);

write(fd[1],"hello" ,5);

char buff[128] = {0};
read(fd[0],buff,127);

printf("buff = %s\n",buff);

close(fd[0]);
clsoe(fd[1]);

exit(0);

}

//彻底关闭时需要关闭父子进程的所有文件描述符

2.父进程只写,子进程只读

int main()
{
int fd[2] = 0;
assert( pipe(fd)  != -1);

if( pid ==0 )
{
close(fd[1]);
while(1)
{
char buff[128] = {0};//buff存放数据
if(read (fd[0],buff,127) ==0)//读取数据,知道返回值为零退出
{
break;
}
printf("child buff=%s\n",buff);
}
close(fd[0]);
exit(0);
}
else
{
close(fd[0]);
while(1)
{
char buff[128] = {0};
fgets(buff,128,stdin);//从键盘获取数据,

if(strcmp(buff,"end",3) == 0)//只要不是end就写入数据
{
break;
}

write(fd[1],buff,strlen(buff));
}
close(fd[1]);
exit(0);
}
}

问题:

1.进程间的通讯有哪几种?
答:管道,信号量,共享内存是在一台主机上进行通讯,socket两台电脑上通讯(网络通讯)
2.进程间的通讯含义?
在A与B彼此隔离的情况下,通过某种机制来达到A与B之间的交流
3.有名管道与无名管道的区别?
有名管道是在任意两个进程间通信,无名是在父子进程间通信
4.写入管道的数据在哪里?
答:内存中,有名管道的大小一直为零,创建的文件一直在磁盘中存放着,打开创建的文件,写入的数据是在内存中
5,管道是什么通信方式
答:半双工

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值