FIFO实例
来源:互联网 发布:php oa办公系统源码 编辑:程序博客网 时间:2024/03/28 17:05
fifo.c 页面源代码:
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <string.h>
#include <fcntl.h>
#include <errno.h>
#include <sys/time.h>
#include <unistd.h>
#define FIFO "/tmp/fifo.temp1"
#define MAXLINE 1024
int main(void)
{
int fifo, fd;
char buf[MAXLINE];
int len;
fd_set set;
struct timeval tv;
int i = 0;
unlink(FIFO); //如果FIFO存在,就先删除
if ((fifo = mkfifo(FIFO, O_RDWR)) < 0) //产生一个有名管道
{
printf("mkfifo error: %s/n", strerror(errno));
return(0);
}
if ((fd = open(FIFO, O_RDWR)) < 0) //读写打开有名管道
{
printf("open error: %s/n", strerror(errno));
return(0);
}
FD_ZERO(&set);
FD_SET(fd, &set);
tv.tv_sec = 5;
tv.tv_usec = 0; //超时设置,超过5秒没有信息,就打印超时
while (1)
{
FD_SET(fd, &set);
if ((i = select(fd + 1, &set, NULL, NULL, &tv)) > 0)//检测管道是否信息
{
printf("receive data/n");
if (FD_ISSET(fd, &set))
{
len = read(fd, buf, MAXLINE);//读取信息
buf[len] = '/0';
printf("buf = %s/n", buf);
tv.tv_sec = atoi(buf);
tv.tv_usec = 0;
}
}
else if (i == 0)
{
tv.tv_sec = 5;
tv.tv_usec = 0;
printf("chaoshi/n");
}
else
printf("error/n");
}
unlink(FIFO); //删除有名管道
return(0);
}
fifo_cli.c页面源代码
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <string.h>
#include <fcntl.h>
#include <errno.h>
#define FIFO "/tmp/fifo.temp1"
#define MAXLINE 1024
int main(void)
{
int fifo;
char buf[MAXLINE];
int len;
int i = 0;
strcpy(buf, "10");
if ((fifo = open(FIFO, O_RDWR)) < 0) //读写打开有名管道
{
printf("mkfifo error: %s/n", strerror(errno));
return(0);
}
while (i < 10)
{
sprintf(buf, "%d", i + 1);
len = write(fifo, buf, strlen(buf)); //写入信息到管道中
printf("send len = %d/n", len);
sleep(i);
i++;
}
return(0);
}
编译:
#gcc -o fifo fifo.c
#gcc -o fifo_cli fifo_cli.c
先运行./fifo,在运行./fifo_cli
程序效果:
fifo_cli将信息通过管道发送给fifo,fifo将信息显示出来。fifo_cli发送10次信息,即0、1、2 ..... 9
fifo接受后可以显示,显示10次以后无数据接受,显示“chaoshi”,需要用kill命令删除进程
- FIFO实例
- FIFO实例
- 有名管道FIFO实例
- fifo实例编程
- FIFO父子进程通信实例
- Linux学习之——FIFO实例
- FIFO
- FIFO
- fifo
- FIFO
- FIFO
- fifo
- FIFO
- FIFO
- fifo
- FIFO
- FIFO
- fifo
- [VC/MFC]时间处理
- 浅淡c#中的webbrowser控件
- android中发送短信
- Mock的基本概念和方法
- 方正快速开发平台ES2007数据导入功能问题总结
- FIFO实例
- Multiple-item widgets
- 【方正中间件】用平台如何进行连远程服务器开发(JAVA版本/数据库SQLServer)
- 2011 1-8
- do while(FLASE)的妙用【转】
- 加载spring时applicationContext.xml文件出错
- 软件分层
- win7下cygwin + Eclipse + Lucene3.1.0 安装编译
- 来自李开复的关于写简历的建议