Given an arbitrary file descriptor, can I make it blocking if it is non-blocking? If so, how?
+7
A:
Its been a while since I played with C, but you could use the fcntl() function to change the flags of a file descriptor:
#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);
Andre Miller
2009-05-27 08:08:02
Yeah, this is the accepted method. Good answer and nice, terse approach to doing the fcntl with the ~O_NONBLOCK. :)
BobbyShaftoe
2009-05-27 11:34:30
+4
A:
I would expect simply non-setting the O_NONBLOCK
flag should revert the file descriptor to the default mode, which is blocking:
/* 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;
}
unwind
2009-05-27 08:10:33