【发布时间】:2014-05-12 06:10:35
【问题描述】:
我有两个程序来写入和读取 FIFO。一个是读取(O_RDONLY)一个 FIFO。另一个是将数据写入这个 FIFO。这是代码:
读取:可执行文件名为读取。
#include<errno.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<stdio.h>
#include<string.h>
int main(int argc, char *argv[])
{
int fd, nread;
const char *pipe_file = "/tmp/test_fifo";
char buf[0x100] ;
fd = open(pipe_file, O_RDONLY);
while(1) {
printf("\n"); /* */
memset(buf, 0, 100);
nread = read(fd, buf, 0x100);
printf("data is %s", buf);
sleep(1);
}
return 0;
}
Write:可执行文件名为write。
#include<errno.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<stdio.h>
#include<string.h>
int main(int argc, char *argv[])
{
int fd;
int num = 1234;
char *s = "changzhi";
const char *pipe_file = "/tmp/test_fifo";
fd = open(pipe_file, O_WRONLY);
write(fd, s, strlen(s));
return 0;
}
名为 /tmp/test_fifo 的 FIFO 已存在。当我运行 read 读取 FIFO 并运行 write 写入 FIFO 时,一切正常。 但是,当读取代码中没有printf("\n"); 时,read 无法读取数据。我不知道为什么。有人可以帮助我吗?非常感谢!
【问题讨论】:
-
请注意,有系统提供的命令称为
read和write。你确定你没有不小心使用其中之一吗? (例如,如果你使用./read和./write,你会没事的。)在你的代码中,你不检查你的打开是否成功;您没有报告您的打开成功;你不检查你的读或写操作是否成功;当写入成功时,您不会报告。您需要并行运行程序:./read & ./write或./write & ./read。