linux C 四、进程间通信(有名管道、共享内存、消息队列)

一、有名管道
对应管道文件,可用于任意进程之间进行通信,打开管道时可指定读写方式,通过文件IO操作,内容存放在内存中。

1.1 API
#include <unistd.h>
#include <fcntl.h>
int mkfifo(const char *path, mode_t mode);

成功时返回0,失败时返回EOF
path 创建的管道文件路径
mode 管道文件的权限,如0666

1.2写操作demo
#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
#include <string.h>
#include <fcntl.h>
int main(){
int re;
int fd;
char buf[32];
unlink("/myfifo"); //删除myfifo
re = mkfifo("/myfifo",0666);
if(re==-1){
perror(“mkfifo”);
return -1;
}
fd = open("/myfifo",O_WRONLY);
if(fd<0){
perror(“open”);
return -1;
}
strcpy(buf,“fifo write test”);
while(1){
write(fd,buf,strlen(buf));
sleep(1);
}
}

1.3 读操作
#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
#include <string.h>
#include <fcntl.h>
int main(){
int re;
int fd;
char buf[32];
fd = open("/myfifo",O_RDONLY);
if(fd<0){
perror(“open”);
return -1;
}
while(1){
memset(buf,0,32);
read(fd,buf,32);
printf("%s\n",buf);
sleep(1);
}
}

注释 :
1、管道面试:
(1)、有名管道和无名管道的区别?
有名管道可以在任意两个进程间通信,无名管道只能在父子进程间通信;

(2)、写入管道文件的数据在内存上还是磁盘上?
无论是有名管道还是无名管道,管道文件的数据在内存存放;
p 管道文件 存放在内存中 不可能在磁盘中存储数据 ;临时存放;断电重启关闭程序会丢失数据;
衍生的一个问题:为什么不能通过普通文件实现进程间的通信?
普通文件存放在磁盘上,读写速度慢;磁盘(永久存储)<<内存(临时存储)<<寄存器(速度);磁盘>>内存>>寄存器(容量);

(3)、管道通信方式是单工、半双工还是全双工?
管道通信方式是半双工;
单工:数据传输只支持数据在一个方向上传输;在同一时间只有一方能接受或发送信息

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值