• linux下开发问题汇总


    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.
    ", 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
    ", buf);
                    }
    
                    return 0;
            }
    
            fprintf(stderr, "This should not happen.
    ");
            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.
    ", TIMEOUT);
                    return 0;
            }
            if (fds[0].revents & POLLIN)
                    printf("stdin is readable
    ");
            if (fds[1].revents & POLLOUT)
                    printf("stdout is writable
    ");
    
            return 0;
    }
  • 相关阅读:
    leetcodedp72
    leetcodedp122
    leetcodedp714
    leetcodedp198
    leetcode518dp背包
    leetcodedp188
    leetcodedp309
    leetcodedp583
    leetcode123
    leetcodedp213
  • 原文地址:https://www.cnblogs.com/feilv/p/5593276.html
Copyright © 2020-2023  润新知