【发布时间】:2009-05-27 07:49:11
【问题描述】:
给定一个任意文件描述符,如果它是非阻塞的,我可以让它阻塞吗?如果有,怎么做?
【问题讨论】:
-
什么样的文件描述符?不同类型的文件描述符在被设置为阻塞时行为不一样......
给定一个任意文件描述符,如果它是非阻塞的,我可以让它阻塞吗?如果有,怎么做?
【问题讨论】:
我玩 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 标志应该将文件描述符恢复为默认模式,即阻塞:
/* 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;
}
【讨论】: