如何将文件描述符设置为阻塞模式?

11

给定任意文件描述符,如果它是非阻塞的,我可以将其变为阻塞状态吗?如果可以,如何实现?


什么类型的文件描述符?不同类型的文件描述符在设置阻塞时表现不同... - Y.L.
2个回答

16

我已经有一段时间没有使用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 的方法简洁明了。 :) - BobbyShaftoe

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;
}

我使用这种方式但不起作用 void sendBytes(unsigned char bufferSize) {
int status; digitalWrite(TxEnablePin, HIGH); for (unsigned char i = 0; i < bufferSize; i++){ serialPutchar (fd, comm_buf[i]) ; while(status == 0) status = make_blocking(fd); } digitalWrite(TxEnablePin, LOW); }int make_blocking(int fd) { int flags; flags = fcntl(fd, F_GETFL, 0); if(flags == -1) /* 失败? / return 0; / 清除阻塞标志。 */ flags &= ~O_NONBLOCK; return fcntl(fd, F_SETFL, flags) != -1; }
- mastermind.pk

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接