给定任意文件描述符,如果它是非阻塞的,我可以将其变为阻塞状态吗?如果可以,如何实现?
我已经有一段时间没有使用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;
}