Linux_ select demo

main.c

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/select.h>
#include <sys/time.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>

int main(void)
{
    int fd = 0;
    fd_set read_set;
    struct timeval timeout;
    int ret;
    char buff[80];

    while(1) {
        FD_ZERO(&read_set);
        FD_SET(fd, &read_set);

        timeout.tv_sec = 3;
        timeout.tv_usec = 0;

        ret = select(fd+1, &read_set, 0, 0, &timeout);
        if (ret == -1) {
            printf("select failed!\n");
            exit(1);
        } else if (ret == 0) {
            printf("time out!\n");
            continue;
        } else {
            if (FD_ISSET(fd, &read_set)) {
                ret = read(fd, buff, sizeof(buff));
                buff[ret-1] = 0;   //ªÿ≥µ∑˚“≤±ªº∆»Î∑µªÿ◊‹ ˝÷–
                printf("received:%s, ret=%d\n", buff, ret);

                if (strcmp(buff, "exit") == 0) {
                    break;
                } 
            }
        }       
    }

    close(fd);
    return 0;
}
posted @ 2016-04-01 12:40  夜色下的港湾  Views(343)  Comments(0Edit  收藏  举报