bogon:/home/jackxiang # man fd_set 看到了select的用法,贴了下代码如下:
select.cpp
g++ select.c
select.cpp
#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
#include <sys/types.h>
#include <unistd.h>
int
main(void)
{
fd_set rfds;
struct timeval tv;
int retval;
/* Watch stdin (fd 0) to see when it has input. */
FD_ZERO(&rfds);
FD_SET(0, &rfds);
/* Wait up to five seconds. */
tv.tv_sec = 5;
tv.tv_usec = 0;
retval = select(1, &rfds, NULL, NULL, &tv);
/* Don't rely on the value of tv now! */
if (retval == -1)
perror("select()");
else if (retval)
printf("Data is available now.\n");
/* FD_ISSET(0, &rfds) will be true. */
else
printf("No data within five seconds.\n");
exit(EXIT_SUCCESS);
}
#include <stdlib.h>
#include <sys/time.h>
#include <sys/types.h>
#include <unistd.h>
int
main(void)
{
fd_set rfds;
struct timeval tv;
int retval;
/* Watch stdin (fd 0) to see when it has input. */
FD_ZERO(&rfds);
FD_SET(0, &rfds);
/* Wait up to five seconds. */
tv.tv_sec = 5;
tv.tv_usec = 0;
retval = select(1, &rfds, NULL, NULL, &tv);
/* Don't rely on the value of tv now! */
if (retval == -1)
perror("select()");
else if (retval)
printf("Data is available now.\n");
/* FD_ISSET(0, &rfds) will be true. */
else
printf("No data within five seconds.\n");
exit(EXIT_SUCCESS);
}
g++ select.c
bogon:/home/jackxiang/com/com118 # ./a.out
dir
Data is available now.
bogon:/home/jackxiang/com/com118 # dir
total 24
-rwxr-xr-x 1 root root 7534 Aug 28 13:42 a.out
-rw-r--r-- 1 root root 4980 Aug 28 13:30 com118.c
-rw-r--r-- 1 root root 4056 Aug 27 23:05 com118.c.bak.jackxiang
-rw-r--r-- 1 root root 890 Aug 28 13:42 selectexample.cpp
dir
Data is available now.
bogon:/home/jackxiang/com/com118 # dir
total 24
-rwxr-xr-x 1 root root 7534 Aug 28 13:42 a.out
-rw-r--r-- 1 root root 4980 Aug 28 13:30 com118.c
-rw-r--r-- 1 root root 4056 Aug 27 23:05 com118.c.bak.jackxiang
-rw-r--r-- 1 root root 890 Aug 28 13:42 selectexample.cpp
作者:jackxiang@向东博客 专注WEB应用 构架之美 --- 构架之美,在于尽态极妍 | 应用之美,在于药到病除
地址:http://jackxiang.com/post/3448/
版权所有。转载时必须以链接形式注明作者和原始出处及本声明!
评论列表