|
| 1 | +#include <stdio.h> |
| 2 | +#include <unistd.h> |
| 3 | +#include <fcntl.h> |
| 4 | +#include <pthread.h> |
| 5 | +#include <sys/stat.h> |
| 6 | +#include <sys/types.h> |
| 7 | +#include "debug.h" |
| 8 | + |
| 9 | +#define FIFO_PATH "/tmp/test_fifo" |
| 10 | + |
| 11 | +void *read_fifo1(void *dummy) |
| 12 | +{ |
| 13 | + int fd = open(FIFO_PATH, O_RDONLY); |
| 14 | + int ret; |
| 15 | + char read_buf[1024]; |
| 16 | + |
| 17 | + debug("fifo open for reading ok\n"); |
| 18 | + while ((ret = read(fd, read_buf, 1024)) > 0) |
| 19 | + { |
| 20 | + debug_info("reader got: %s\n", read_buf); |
| 21 | + } |
| 22 | + close(fd); |
| 23 | + |
| 24 | + return NULL; |
| 25 | +} |
| 26 | + |
| 27 | +void *read_fifo2(void *_fd) |
| 28 | +{ |
| 29 | + int fd = dup((int)_fd); |
| 30 | + int ret; |
| 31 | + char read_buf[1024]; |
| 32 | + |
| 33 | + if ((ret = read(fd, read_buf, 1024)) > 0) |
| 34 | + { |
| 35 | + debug_info("reader got: %s\n", read_buf); |
| 36 | + } |
| 37 | + close(fd); |
| 38 | + |
| 39 | + return NULL; |
| 40 | +} |
| 41 | + |
| 42 | + |
| 43 | +void test1() |
| 44 | +{ |
| 45 | + pthread_t tid; |
| 46 | + int fd; |
| 47 | + |
| 48 | + if (access(FIFO_PATH, F_OK) != 0) |
| 49 | + { |
| 50 | + mkfifo(FIFO_PATH, 0666); |
| 51 | + } |
| 52 | + |
| 53 | + pthread_create(&tid, NULL, read_fifo1, NULL); |
| 54 | + |
| 55 | + fd = open(FIFO_PATH, O_WRONLY); |
| 56 | + debug("fifo open for writing ok\n"); |
| 57 | + write(fd, "111", 4); |
| 58 | + close(fd); |
| 59 | + |
| 60 | + pthread_join(tid, NULL); |
| 61 | +} |
| 62 | + |
| 63 | +void test2() |
| 64 | +{ |
| 65 | + pthread_t tid; |
| 66 | + int fd; |
| 67 | + |
| 68 | + fd = open(FIFO_PATH, O_RDWR); |
| 69 | + pthread_create(&tid, NULL, read_fifo2, (void *)fd); |
| 70 | + write(fd, "222", 4); |
| 71 | + sleep(1); |
| 72 | + close(fd); |
| 73 | + pthread_join(tid, NULL); |
| 74 | +} |
| 75 | + |
| 76 | + |
| 77 | +void test3() |
| 78 | +{ |
| 79 | + int fd; |
| 80 | + int ret; |
| 81 | + |
| 82 | + if (access(FIFO_PATH, F_OK) != 0) |
| 83 | + { |
| 84 | + mkfifo(FIFO_PATH, 0666); |
| 85 | + } |
| 86 | + |
| 87 | + if (fork() > 0) |
| 88 | + { |
| 89 | + fd = open(FIFO_PATH, O_WRONLY); |
| 90 | + write(fd, "333", 4); |
| 91 | + close(fd); |
| 92 | + } |
| 93 | + else |
| 94 | + { |
| 95 | + char read_buf[1024]; |
| 96 | + fd = open(FIFO_PATH, O_RDONLY); |
| 97 | + if ((ret = read(fd, read_buf, 1024)) > 0) |
| 98 | + { |
| 99 | + debug_info("reader got: %s\n", read_buf); |
| 100 | + } |
| 101 | + close(fd); |
| 102 | + } |
| 103 | +} |
| 104 | + |
| 105 | + |
| 106 | + |
| 107 | +int main(void) |
| 108 | +{ |
| 109 | + test1(); |
| 110 | + test2(); |
| 111 | + test3(); |
| 112 | + |
| 113 | + return 0; |
| 114 | +} |
| 115 | + |
0 commit comments