FIFO管道通信(linux)
2016-07-21 14:42
369 查看
程序运行前需在linux中使用mkfifo 建立一个管道文件
fifo适合进程间通信
fifowrite.cpp
#include<sys/stat.h>
#include<cstdio>
#include<cstring>
#include<sys/types.h>
#include<iostream>
#include<unistd.h>
#include<cstdlib>
#include<fcntl.h>
void sys_err(const char *str)
{
perror(str);
exit(-1);
}
int main(int argc,char *argv[])
{
int fd,i;
char buf[1024];
if(argc < 2)
{
std::cout<<"execname filename"<<std::endl;
return -1;
}
fd = open(argv[1],O_WRONLY);
if(fd < 0)
{
sys_err("open");
}
i = 0;
while(1)
{
sprintf(buf,"hello %d\n",i++);
write(fd,buf,strlen(buf));
sleep(1);
}
close(fd);
return 0;
}
piforead.cpp
#include<sys/stat.h>
#include<cstdio>
#include<cstring>
#include<sys/types.h>
#include<iostream>
#include<unistd.h>
#include<cstdlib>
#include<fcntl.h>
void sys_err(const char *str)
{
perror(str);
exit(-1);
}
int main(int argc,char *argv[])
{
int fd,len;
char buf[1024];
if(argc < 2)
{
std::cout<<"execname filename"<<std::endl;
return -1;
}
fd = open(argv[1],O_RDONLY);
if(fd < 0)
{
sys_err("open");
}
len = 0;
while(1)
{
len = read(fd,buf,sizeof(buf));
write(STDOUT_FILENO,buf,len);
sleep(1);
}
close(fd);
return 0;
}
fifo适合进程间通信
fifowrite.cpp
#include<sys/stat.h>
#include<cstdio>
#include<cstring>
#include<sys/types.h>
#include<iostream>
#include<unistd.h>
#include<cstdlib>
#include<fcntl.h>
void sys_err(const char *str)
{
perror(str);
exit(-1);
}
int main(int argc,char *argv[])
{
int fd,i;
char buf[1024];
if(argc < 2)
{
std::cout<<"execname filename"<<std::endl;
return -1;
}
fd = open(argv[1],O_WRONLY);
if(fd < 0)
{
sys_err("open");
}
i = 0;
while(1)
{
sprintf(buf,"hello %d\n",i++);
write(fd,buf,strlen(buf));
sleep(1);
}
close(fd);
return 0;
}
piforead.cpp
#include<sys/stat.h>
#include<cstdio>
#include<cstring>
#include<sys/types.h>
#include<iostream>
#include<unistd.h>
#include<cstdlib>
#include<fcntl.h>
void sys_err(const char *str)
{
perror(str);
exit(-1);
}
int main(int argc,char *argv[])
{
int fd,len;
char buf[1024];
if(argc < 2)
{
std::cout<<"execname filename"<<std::endl;
return -1;
}
fd = open(argv[1],O_RDONLY);
if(fd < 0)
{
sys_err("open");
}
len = 0;
while(1)
{
len = read(fd,buf,sizeof(buf));
write(STDOUT_FILENO,buf,len);
sleep(1);
}
close(fd);
return 0;
}
相关文章推荐
- Linux socket 初步
- Linux Kernel 4.0 RC5 发布!
- linux lsof详解
- linux 文件权限
- Linux 执行数学运算
- 10 篇对初学者和专家都有用的 Linux 命令教程
- Linux 与 Windows 对UNICODE 的处理方式
- Ubuntu12.04下QQ完美走起啊!走起啊!有木有啊!
- 解決Linux下Android开发真机调试设备不被识别问题
- 运维入门
- 运维提升
- Linux 自检和 SystemTap
- Ubuntu Linux使用体验
- c语言实现hashmap(转载)
- Linux 信号signal处理机制
- linux下mysql添加用户
- Scientific Linux 5.5 图形安装教程
- Linux 下无损图片压缩小工具介绍