poll函数原型
#include <poll.h>
int poll(struct pollfd *fds, nfds_t nfds, int timeout);
struct pollfd {
int fd; /* file descriptor */
short events; /* requested events */
short revents; /* returned events */
};
测试1:读取输入的例子:
#include<stdio.h>
#include<stdlib.h>
#include <unistd.h>
#include <string.h>
#include <poll.h>
int poll(struct pollfd *fds, nfds_t nfds, int timeout);
#define DEBUG_INFO(format, ...) printf("%s - %d - %s :: "format"\n",__FILE__,__LINE__,__func__ ,##__VA_ARGS__)
#define MAX_FD_COUNT 1
int main(void){
char buf[200];
memset(buf,0,sizeof(buf));
FILE* file = fdopen(0,"r");
int len = fscanf(file,"%s",buf);
DEBUG_INFO("len = %d,buf = %s",len,buf);
return 0;
}
测试2:poll+STDIN_POLL
#include<stdio.h>
#include<stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/poll.h>
int poll(struct pollfd *fds, nfds_t nfds, int timeout);
#define DEBUG_INFO(format, ...) printf("%s - %d - %s :: "format"\n",__FILE__,__LINE__,__func__ ,##__VA_ARGS__)
#define MAX_FD_COUNT 1
int main(void){
char buf[BUFSIZ];
struct pollfd fds[1];
memset(buf,0,sizeof(buf));
DEBUG_INFO("%d,%d,%d",STDIN_FILENO, STDOUT_FILENO,STDERR_FILENO);
fds[0].fd = STDIN_FILENO;
fds[0].events = POLLIN;
int ret = 0;
while(1){
ret = poll(fds,1,30000);
if(ret == -1){
perror("error");
exit(-1);
}
if(fds[0].revents & POLLIN){
int len = read(STDIN_FILENO,buf,sizeof(buf));
DEBUG_INFO("len = %d,buf = %s",len,buf);
if(len == 1){
break;
}
}
}
DEBUG_INFO("bye bye");
return 0;
}
测试3:poll+函数fileno+stdin
#include <stdio.h>
int fileno(FILE *stream);
测试代码:
#include<stdio.h>
#include<stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/poll.h>
int poll(struct pollfd *fds, nfds_t nfds, int timeout);
#define DEBUG_INFO(format, ...) printf("%s - %d - %s :: "format"\n",__FILE__,__LINE__,__func__ ,##__VA_ARGS__)
#define MAX_FD_COUNT 1
int main(void){
char buf[BUFSIZ];
struct pollfd fds[1];
memset(buf,0,sizeof(buf));
int fd = fileno(stdin);
DEBUG_INFO("fd = %d",fd);
fds[0].fd = fd;
fds[0].events = POLLIN;
int ret = 0;
while(1){
ret = poll(fds,1,30000);
if(ret == -1){
perror("error");
exit(-1);
}
if(fds[0].revents & POLLIN){
int len = read(fd,buf,sizeof(buf));
DEBUG_INFO("len = %d,buf = %s",len,buf);
if(len == 1){
break;
}
}
}
DEBUG_INFO("bye bye");
return 0;
}
测试及结果:
/big/work/ipc/poll_mkstemp.c - 19 - main :: fd = 0
123456
/big/work/ipc/poll_mkstemp.c - 31 - main :: len = 7,buf = 123456
^C
real 0m7.472s
user 0m0.001s
sys 0m0.000s
小结
鸡肋还是积累。大梦谁先觉,平生我自知。