代码之家  ›  专栏  ›  技术社区  ›  Joel

如何使文件描述符阻塞?

  •  11
  • Joel  · 技术社区  · 17 年前

    给定一个任意的文件描述符,如果它是非阻塞的,我可以让它阻塞吗?如果是这样,怎么办?

    2 回复  |  直到 8 年前
        1
  •  16
  •   Andre Miller    17 年前

    我已经有一段时间没玩C了,但你可以用 fcntl() 函数用于更改文件描述符的标志:

    #include <unistd.h>
    #include <fcntl.h>
    
    // Save the existing flags
    
    saved_flags = fcntl(fd, F_GETFL);
    
    // Set the new flags with O_NONBLOCK masked out
    
    fcntl(fd, F_SETFL, saved_flags & ~O_NONBLOCK);
    
        2
  •  8
  •   unwind    17 年前

    O_NONBLOCK flag应将文件描述符还原为默认模式,即阻塞:

    /* Makes the given file descriptor non-blocking.
     * Returns 1 on success, 0 on failure.
    */
    int make_blocking(int fd)
    {
      int flags;
    
      flags = fcntl(fd, F_GETFL, 0);
      if(flags == -1) /* Failed? */
       return 0;
      /* Clear the blocking flag. */
      flags &= ~O_NONBLOCK;
      return fcntl(fd, F_SETFL, flags) != -1;
    }