cfileunixblocking

How to create blocking file descriptor in Unix?


I would like to create blocking and non-blocking file descriptors in Unix's C. First, blocking:

fd = open("file.txt", O_CREAT | O_WRONLY | O_EXCL);

Is that right? Shouldn't I add some mode options, like 0666 for example?

How about non-blocking file? I have no idea for this.

I would like to achieve something like:

  1. When I open it to write in it, and it's opened for writing, it's ok; if not, it blocks.
  2. When I open it to read from it, and it's opened for reading, it's ok; if not, it blocks.

Solution

  • File descriptors are blocking or non-blocking; files are not. Add O_NBLOCK to the options in the open() call if you want a non-blocking file descriptor.

    Note that opening a FIFO for reading or writing will block unless there's a process with the FIFO open for the other operation, or you specify O_NBLOCK. If you open it for read and write, the open() is non-blocking (will return promptly); I/O operations are still controlled by whether you set O_NBLOCK or not.

    The updated question is not clear. However, if you're looking for 'exclusive access to the file' (so that no-one else has it open), then neither O_EXCL nor O_NBLOCK is the answer. O_EXCL affects what happens when you create the file; the create will fail if the file already exists. O_NBLOCK affects whether a read() operation will block when there's no data available to read. If you read the POSIX open() description, there is nothing there that allows you to request 'exclusive access' to a file.

    To answer the question about file mode: if you include O_CREAT, you need the third argument to open(). If you omit O_CREAT, you don't need the third argument to open(). It is a varargs function:

    int open(const char *filename, int options, ...);