首页 > 系统服务 > 详细

linux 管道通信

时间:2015-06-12 17:00:17      阅读:238      评论:0      收藏:0      [点我收藏+]

  下面举linux下有名管道通信的代码。

-----------------------------------------

fifo_read.c

===========

#include<errno.h>
#include<stdio.h>
#include<memory.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#define FIFO "myfifo"

int main(void)
{
int fd;
int num;
char buff[100];
if(access(FIFO,F_OK) == -1)
{
mkfifo(FIFO,0777);
}
fd = open(FIFO,O_RDONLY|O_NONBLOCK);
if(fd < 0)
{
printf("open fifo error:%s\n",strerror(errno));
}
printf("open fifo fd=%d\n",fd);
while(1)
{
num=0;
memset(buff,‘\0‘,100);
num=read(fd,buff,100);
if(num<0)
{
printf("read fifo:%s\n",strerror(errno));
}
else if(num==0)
{
printf("no data to read.\n");
}
else
{
printf("read [%d] bytes in fifo,it is [%s].\n",num,buff);
}
sleep(1);
}
return 0;
}

 

 

----------------------

fifo_write.c

==========

#include<stdio.h>
#include<fcntl.h>
#include<memory.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#define FIFO "myfifo"

int main(void)
{
int fd;
char buff[100];
int num =0;
if(access(FIFO,F_OK)== -1)
{
mkfifo(FIFO,0777);
}
fd = open(FIFO,O_WRONLY);
if(fd < 0)
{
printf("open fifo error!\n");
}
printf("open file fd=%d\n",fd);
while(1)
{
memset(buff,‘\0‘,100);
num=0;
printf("please write less than 100 letters:\n");
scanf("%s",buff);
num= write(fd,buff,strlen(buff));
printf("[%d] letters is written,it is [%s]\n",num,buff);
sleep(1);
}
return 0;
}

linux 管道通信

原文:http://www.cnblogs.com/sunzl1987/p/4571775.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!