Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a file descriptor blocking?

Tags:

c

unix

file-io

Given an arbitrary file descriptor, can I make it blocking if it is non-blocking? If so, how?

like image 702
Joel Avatar asked May 27 '09 07:05

Joel


People also ask

Is read () a blocking call?

Note: The default mode is blocking. If data is not available to the socket, and the socket is in blocking and synchronous modes, the READ call blocks the caller until data arrives.

Is write () a blocking call?

Normally, write() will block until it has written all of the data to the file. If you try to write data to a pipe with a full internal buffer, your write() will not return until someone has read enough out of the pipe to make room for all of the data that you're trying to add.

How is a file descriptor created?

When a process makes a successful request to open a file, the kernel returns a file descriptor which points to an entry in the kernel's global file table. The file table entry contains information such as the inode of the file, byte offset, and the access restrictions for that data stream (read-only, write-only, etc.).

What happens when you close a file descriptor?

close() closes a file descriptor, so that it no longer refers to any file and may be reused. Any record locks (see fcntl(2)) held on the file it was associated with, and owned by the process, are removed (regardless of the file descriptor that was used to obtain the lock).


1 Answers

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);
like image 172
Andre Miller Avatar answered Sep 18 '22 20:09

Andre Miller