- 论坛徽章:
- 0
|
非阻塞读FIFO的程序: read_fifo.c
- #include <sys/types.h>
- #include <sys/stat.h>
- #include <unistd.h>
- #include <fcntl.h>
- #include <errno.h>
- #define FIFO_PATH "/tmp/test_fifo"
- #define LEN 1000
- int main(void)
- {
- int fd, n;
- char buf[LEN] ;
- if (mkfifo(FIFO_PATH, 0600) < 0) { // 创建FIFO
- if (errno != EEXIST) {
- perror("mkfifo");
- exit(-1);
- }
- }
- if ((fd = open(FIFO_PATH, O_RDONLY|O_NONBLOCK)) < 0) { // 非阻塞读打开FIFO
- perror("open fifo");
- exit(-1);
- }
- while(1) { // 循环读FIFO
- n = read(fd, buf, LEN);
- printf("n = %d\n", n);
- if (n < 0) { // 读错误,退出
- perror("read");
- exit(-1);
- }
- if (n == 0) { // 未读到数据, 休眠2秒, 继续读
- sleep(2);
- continue;
- }
- }
- close(fd);
- return 0;
- }
复制代码
阻塞写FIFO的程序: write_fifo.c
- #include <sys/types.h>
- #include <sys/stat.h>
- #include <unistd.h>
- #include <fcntl.h>
- #include <errno.h>
- #define FIFO_PATH "/tmp/test_fifo"
- #define LEN 6800
- int main(void)
- {
- int fd, n;
- int sum = 0;
- char buf[LEN] ;
- if ((fd = open(FIFO_PATH, O_WRONLY)) < 0) { // 阻塞只写方式打开FIFO
- perror("open fifo");
- exit(-1);
- }
- // 循环写,直到把全部数据写完
- while(1) {
- n = write(fd, &buf[sum], LEN-sum); // 写FIFO
- printf("n = %d\n", n);
- if (n < 0) { // 写错误退出
- perror("read");
- exit(-1);
- }
- sum += n; // 累加已经写的字节数
- if (sum == LEN) // 如果已经写完,退出
- break;
- }
- printf("sum = %d\n", sum);
- close(fd);
- return 0;
- }
复制代码
运行结果:
read_fifo的输出:
n = 0
n = 1000
n = 1000
n = 1000
n = 1000
n = 96
n = -1
read: Resource temporarily unavailable
write_fifo的输出:
n = 4096
断开的管道
请教什么原因产生的这种错误?
PS: 也不是总是产生错误, 有时也会正确运行
[ 本帖最后由 grt8000 于 2006-6-22 17:13 编辑 ] |
|