2009-05-27 58 views

回答

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); 
+0

是的,这是公认的方法。很好的回答,以及用〜O_NONBLOCK做fcntl的简洁方法。 :) – BobbyShaftoe 2009-05-27 11:34:30

7

我希望只是不设置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; 
}