9
给定一个任意的文件描述符,如果它是非阻塞的,我可以阻止它吗?如果是这样,怎么样?在c中,如何使文件描述符阻塞?
给定一个任意的文件描述符,如果它是非阻塞的,我可以阻止它吗?如果是这样,怎么样?在c中,如何使文件描述符阻塞?
它已经有一段时间我打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;
}
是的,这是公认的方法。很好的回答,以及用〜O_NONBLOCK做fcntl的简洁方法。 :) – BobbyShaftoe 2009-05-27 11:34:30