如何阻止文件描述符?

Joe*_*oel 10 c unix file-io

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

And*_*ler 14

自从我使用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);
Run Code Online (Sandbox Code Playgroud)


unw*_*ind 8

我希望只是非设置O_NONBLOCK标志应该将文件描述符恢复为默认模式,这是阻塞:

/* 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;
}
Run Code Online (Sandbox Code Playgroud)