• 《UNIX网络编程》 -- 第六章


    6.3 select 函数

    给出描述符1、4、5而 maxfdp1 设置为6的原因:

    maxfdp1 是值-结果参数,这里传递的是描述符的范围,类似之前的 size_of(length)。又因为描述符是从 0 开始,最大的描述符是5,所以有5 + 1 = 6个。

    根据 select 文档

    On exit, each of the file descriptor sets is modified in place to
           indicate which file descriptors actually changed status.  (Thus, if
           using select() within a loop, the sets must be reinitialized before
           each call.)

    为什么要根据 FD_ISSET 来重新初始化?比如监听 1、4、5:

    返回 1 完成了事件;

    那就只需要监听剩余的 4、5了吧?怎么做?

    看到后面有点明白了,通过 FD_ISSET 判断是哪个 fd 事件完成了,然后转到对应的处理代码中。

    sigmask 参数

    为什么会死锁?

    poll 

    返回值

    On success, a positive number is returned; this is the number of
    structures which have nonzero revents fields (in other words, those
    descriptors with events or errors reported). A value of 0 indicates
    that the call timed out and no file descriptors were ready. On
    error, -1 is returned, and errno is set appropriately.

    nready = Poll(client, maxi+1, INFTIM);  

    maxi+1 为 ndfs 参数,表示 the number of items in the fds array

    使用  & 检查 revents 事件:

    if (client[i].revents & (POLLRDNORM | POLLERR))
    

    总结 select 和 poll

    当有事件通知时,select 和 poll 都需要检查所有在检测的 fd,然后给每个 fd 写处理事件。

    比如,这里分为 listenfd 和 connfd,所以 listenfd 是一种处理方法,而所有的 connfd 是一种处理方法。

     习题

    6.1 

    将描述符集的第一个元素的指针地址赋值给另一个描述符集。

    描述符集出现在 6.3节

    参考答案 

    这个整数数组包含在一个结构中,而C是允许结构跨等号赋值的

    6.2 

    这里的 select 返回正值,是说明有多少个描述符满足了“可写”条件。

    参考答案

    为什么避免阻塞就能返回正值,阻塞完成后不会返回正值吗?

    6.3 

    加上 else,就变成了 else if。

    那么,当满足 if (FD_ISSET(sockfd, &rset)) 之后,就不会执行 19 行的代码了。而现在的情况是,检查完 14 行的代码,还要检查 19 行的代码条件是否满足,这两个条件是不相关的。

    参考答案

    我的答案并没有考虑到这个是无限循环,并且 sock 并不会总是可读,所以 fp 一定会有能够执行的时候。

    6.4 

    获取内核允许的最多描述符数;

    通过 setrlimit 将软限制设置为硬限制

       // Define and object of structure 
       // rlimit. 
       struct rlimit rl; 
      
       // First get the limit on open files 
       getrlimit (RLIMIT_NOFILE, &rl); 
      
     
       // Change the limit 
       rl.rlim_cur = rl.rlim_max;
      
       // Now call setrlimit() to set the  
       // changed value. 
       setrlimit (RLIMIT_NOFILE, &rl); 
    

      来源:getrlimit() and setrlimit() to Control System Resources on Linux

    6.5

     题目麻烦,现在不想做。

    shutdown

    shutdown(sockfd, SHUT_RD);
    

    MacOS 使用 tcpdump,又要学这个的用法,现在也不想学。

    参考答案  

    6.6

    6.7

  • 相关阅读:
    C 实战练习题目45
    C 实战练习题目44
    C 实战练习题目43
    C 实战练习题目42 -auto定义变量
    C 实战练习题目41 -static定义静态变量
    如何0基础学习C/C++?
    2019-11-29-win10-uwp-关联文件
    2019-11-29-win10-UWP-Controls-by-function
    2019-11-29-WPF-高性能笔
    2019-11-29-WPF-使用-Win2d-渲染
  • 原文地址:https://www.cnblogs.com/jay54520/p/6991480.html
Copyright © 2020-2023  润新知