linux下网络编程学习
http://blog.csdn.net/Simba888888/article/category/1426325
select()使用例子
#include <stdio.h> #include <sys/time.h> #include <sys/types.h> #include <unistd.h> #define TIMEOUT 5 #define BUF_LEN 1024 int main(void) { struct timeval tv; fd_set rfds; int ret; FD_ZERO(&rfds); FD_SET(STDIN_FILENO, &rfds); tv.tv_sec = TIMEOUT; tv.tv_usec = 0; ret = select(STDIN_FILENO+1, &rfds, NULL, NULL, &tv); if (ret == -1) { perror("select()"); return 1; } else if (!ret) { printf("%d seconds elapsed.\n", TIMEOUT); return 0; } if (FD_ISSET(STDIN_FILENO, &rfds)) { char buf[BUF_LEN+1]; int len; len = read(STDIN_FILENO, buf, BUF_LEN); if (len == -1) { perror("read()"); return 1; } if (len) { buf[len] = 0; printf("read: %s\n", buf); } return 0; } fprintf(stderr, "This should not happen.\n"); return 1; }
poll()使用例子
#include <stdio.h> #include <unistd.h> #include <poll.h> #define TIMEOUT 5 int main(void) { struct pollfd fds[2]; int ret; fds[0].fd = STDIN_FILENO; fds[0].events = POLLIN; fds[1].fd = STDOUT_FILENO; fds[1].events = POLLOUT; ret = poll(fds, 2, TIMEOUT*1000); if (ret == -1) { perror("poll()"); return 1; } if (!ret) { printf("%d seconds elapsed.\n", TIMEOUT); return 0; } if (fds[0].revents & POLLIN) printf("stdin is readable\n"); if (fds[1].revents & POLLOUT) printf("stdout is writable\n"); return 0; }