在qnx下使用fifo在两个进程之间共享数据的例子:
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <iostream>
//int mkfifo( const char* path,
// mode_t mode );
int main(void)
{
int ret,fd,pid;
ret = mkfifo("/var/fifo1",S_IRUSR | S_IWUSR);
std::cout << "ret: " << ret << std::endl;
pid = fork();
if (pid > 0) {
std::cout << "- parent -" << std::endl;
fd = open("/var/fifo1",O_RDONLY,0);
if(fd < 0){
std::cout << "open error!\n" ;
return -1;
}
char buf1[500];
while(1) {
std::cout << "please waiting...\n";
ssize_t s = read(fd,buf1,sizeof(buf1)-1);
if(s > 0) {
buf1[s-1] = 0;
std::cout << "Server recv: " << buf1 << std::endl;
} else if (s == 0) {
std::cout << "client quit,exit ..." << std::endl;
break;
}
}
} else if (pid == 0){
std::cout << "- child -" << std::endl;
fd = open("/var/fifo1",O_WRONLY,0);
if(fd < 0){
std::cout << "open error!\n" ;
return -1;
}
char buf1[500];
while(1) {
std::cout << "client\n";
fflush(stdout);
ssize_t s = read(0,buf1,sizeof(buf1)-1);//向管道文件中写数据
if(s > 0) {
buf1[s] = 0;//以字符串的形式写
write(fd,buf1,strlen(buf1));
}
}
} else {
std::cout << "fork error!\n" ;
}
std::cout << "file is exit!\n" ;
close(ret);
}
|