3.2 进程间通信之fifo
2024-09-17 09:29:41
一、引言
FIFO常被称为有名管道,不同于管道(pipe)。pipe仅适用于“有血缘关系”的IPC。但FIFO还可以应用于不相关的进程的IPC。实际上,FIFO是Linux基础文件类型中的一种,是在读写内核通道。
函数原型:
int mkfifo(const char *pathname, mode_t mode); 成功返回 0, 失败返回 -
命令:
mkfifo + 管道名 例:mkfifo fifo_one
操作步骤:
1) 通过命令行创建fifo;
2) 使用open、close、read、write等I/O函数操作fifo。
二、例程
1) 创建fifi:
#mkfifio fifo_one
2) fifo 写函数
#include <stdio.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>
#include <stdlib.h>
#include <string.h> void sys_err(char *str)
{
perror(str);
exit(-);
}
int main(int argc, char *argv[])
{
int fd, i;
char buf[]; if (argc < ) {
printf("Please enter: ./a.out fifoname\n");
return -;
}
fd = open(argv[], O_WRONLY);//打开fifo
if (fd < )
sys_err("open"); i = ;
while () {
printf("write fifo \n ");
9 sprintf(buf, "hello itcast %d\n", i++); //格式化输出到buf
write(fd, buf, strlen(buf)); //向fifo写入buf
sleep();
}
close(fd); return ;
}
3) fifo 读函数
#include <stdio.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>
#include <stdlib.h>
#include <string.h> void sys_err(char *str)
{
perror(str);
exit();
} int main(int argc, char *argv[])
{
int fd, len;
char buf[]; if (argc < ) {
printf("Please enter: ./a.out fifoname\n");
return -;
}
fd = open(argv[], O_RDONLY);//打开fifo
if (fd < )
sys_err("open");
while () {
len = read(fd, buf, sizeof(buf));//从fifo读取数据到buf
write(STDOUT_FILENO, buf, len); //将buf写入标准输出
sleep(); //多個读端时应增加睡眠秒数,放大效果.
}
close(fd);
return ;
}
编译执行:
最新文章
- PhpStorm 2016.3 For Mac 重大里程碑更新 -- 终于解决了不能输入中文标点符号的重大bug
- html和css的编码规范
- 【cruch bang】中切换成左手鼠标
- Lucene/ElasticSearch 学习系列 (1) 为什么学,学什么,怎么学
- Backbone
- insert into select 堵塞update
- PHP实现单击“添加”按钮增加一行表单项,并将所有内容插入到数据库中
- asp.net MVC2.0学习笔记
- C++ 顺序容器 vector list deque 之比较
- (简单) POJ 3264 Balanced Lineup,RMQ。
- Eclipse中GIT插件更新工程到之前版本
- 51nod_1120:机器人走方格 V3
- adb pull 报错处理:adb: error: cannot create file/directory &#39;E:\&#39;: No such file or directory
- Logical Volume Manager (LVM)
- centos7 yum安装ffmpeg,以及ffmpeg的简单用法
- linux 查看信息-磁盘分区&;网络
- maven +bootstrap+ssm
- 分布式监控系统Zabbix-3.0.3--短信报警设置
- SQL Server 如何添加删除外键、主键,以及更新自增属性
- 编译 php-memcache 扩展时提示Cannot find autoconf