| #include <string.h> |
| #include <stdio.h> |
003 | #include <sys/types.h> |
004 | #include <sys/stat.h> |
005 | #include <fcntl.h> |
006 | #include <errno.h> |
007 | #include <poll.h> |
008 |
009 | /* int poll(struct pollfd *fds, nfds_t nfds, int timeout); */ |
010 |
011 | /* |
012 | struct pollfd { |
013 | int fd; // file descriptor |
014 | short events; // requested events |
015 | short revents; // returned events |
016 | }; |
017 | */ |
018 | /* |
019 | The bits that may be set/returned in events and revents are defined in |
020 | <poll.h>: |
021 | POLLIN: There is data to read.(数据可读) |
022 | POLLOUT:Writing now will not block.(数据可读) |
023 | */ |
024 |
025 | #define OPEN_FLAGS O_RDWR|O_CREAT |
026 | #define OPEN_MODE 00777 |
027 |
028 | #define W_DATA "howaylee" |
029 |
030 | int main( int argc, char * argv[]) |
031 | { |
032 | int ret = -1; |
033 | int fd1 = -1; |
034 | int fd2 = -1; |
035 |
036 | char r_buf[12] = {0}; |
037 |
038 | struct pollfd fds[2] = {0}; |
039 |
040 | //open fd1 |
041 | fd1 = open(argv[1], OPEN_FLAGS, OPEN_MODE); |
042 | if (-1 == fd1) |
043 | { |
044 | perror ( "open fd1 failed: " ); |
045 | return -1; |
046 | } |
047 | //write fd1 |
048 | ret = write(fd1, W_DATA, sizeof (W_DATA)); |
049 | if (-1 == ret) |
050 | { |
051 | perror ( "write fd1 failed: " ); |
052 | goto _OUT; |
053 | } |
054 | //lseek fd1 head |
055 | ret = lseek(fd1, 0, SEEK_SET); |
056 | if (-1 == ret) |
057 | { |
058 | perror ( "lseek fd1 failed: " ); |
059 | goto _OUT; |
060 | } |
061 |
062 | //open fd2 |
063 | fd2 = open(argv[2], OPEN_FLAGS, OPEN_MODE); |
064 | if (-1 == fd2) |
065 | { |
066 | perror ( "open fd2 failed: " ); |
067 | return -1; |
068 | } |
069 |
070 | /*阻塞,等待程序读写操作*/ |
071 |
072 |
073 | while (1) |
074 | { |
075 | //初始化pollfd |
076 | fds[0].fd = fd1; |
077 | //可读 |
078 | fds[0].events = POLLIN; |
079 |
080 | fds[1].fd = fd2; |
081 | //可写 |
082 | fds[1].events = POLLOUT; |
083 |
084 | //poll |
085 | ret = poll(fds, sizeof (fds)/ sizeof (fds[0]), -1); |
086 | if (-1 == ret) |
087 | { |
088 | perror ( "poll failed: " ); |
089 | goto _OUT; |
090 | } |
091 |
092 | //read fd1 |
093 | if (fds[0].revents & POLLIN ) |
094 | { |
095 | //清空缓存 |
096 | //memset(r_buf, 0, sizeof(r_buf)); |
097 | ret = read(fd1, r_buf, sizeof (r_buf)); |
098 | if (-1 == ret) |
099 | { |
100 | perror ( "poll read failed: " ); |
101 | goto _OUT; |
102 | } |
103 | printf ( "read = %s\n" , r_buf); |
104 | } |
105 |
106 | //write fd2 |
107 | if (fds[1].revents & POLLOUT ) |
108 | { |
109 | ret = write(fd2, r_buf, sizeof (r_buf)); |
110 | if (-1 == ret) |
111 | { |
112 | perror ( "poll write failed: " ); |
113 | goto _OUT; |
114 | } |
115 | printf ( "write = %s\n" , r_buf); |
116 | } |
117 | } |
118 |
119 | //close fd1 fd2 |
120 | close(fd1); |
121 | close(fd2); |
122 |
123 | _OUT: |
124 | return ret; |
125 | } |