What is the purpose of calling fcntl() be called with the file descriptor as -1 and cmd as F_GETFL?

42_huh picture 42_huh · May 15, 2013 · Viewed 14k times · Source

I am trying to understand what this line of code means:

flags = fcntl(-1,F_GETFL,0);

Answer

Jonathan Leffler picture Jonathan Leffler · May 15, 2013

The usual reason for calling fcntl() with the F_GETFL flag is to modify the flags and set them with fcntl() and F_SETFL; the alternative reason for calling fcntl() with F_GETFL is to find out the characteristics of the file descriptor. You can find the information about which flags can be manipulated by reading (rather carefully) the information about <fcntl.h>. The flags include:

  • O_APPEND — Set append mode.
  • O_DSYNC — Write according to synchronized I/O data integrity completion.
  • O_NONBLOCK — Non-blocking mode.
  • O_RSYNC — Synchronized read I/O operations.
  • O_SYNC — Write according to synchronized I/O file integrity completion.

Plus (POSIX 2008) O_ACCMODE which can then be used to distinguish O_RDONLY, O_RDWR, and O_WRONLY, if I'm reading the referenced pages correctly.

However, it makes no sense whatsoever to call fcntl() with a definitively invalid file descriptor such as -1. All that happens is that the function returns -1 indicating failure and sets errno to EBADF (bad file descriptor).