【问题标题】:How to make a file descriptor blocking?如何使文件描述符阻塞?
【发布时间】:2009-05-27 07:49:11
【问题描述】:

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

【问题讨论】:

  • 什么样的文件描述符?不同类型的文件描述符在被设置为阻塞时行为不一样......

标签: c unix file-io


【解决方案1】:

我玩 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);

【讨论】:

  • 是的,这是公认的方法。使用 ~O_NONBLOCK 执行 fcntl 的好答案和简洁的方法。 :)
【解决方案2】:

我希望简单地不设置 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;
}

【讨论】:

  • 我正在使用这种方式但没有工作 void sendBytes(unsigned char bufferSize) { int status;数字写入(TxEnablePin,高); for (unsigned char i = 0; i /返回0; / 清除阻塞标志。 */ 标志 &= ~O_NONBLOCK;返回 fcntl(fd, F_SETFL, 标志) != -1; }
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-19
  • 2019-11-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-07-15
相关资源
最近更新 更多