What is the purpose of calling fcntl () to call with a file descriptor like -1 and cmd like F_GETFL?

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

flags = fcntl(-1,F_GETFL,0); 
+6
source share
3 answers

A common reason for calling fcntl() with the F_GETFL flag is to change the flags and set them with fcntl() and F_SETFL ; An alternative reason to call fcntl() with F_GETFL is to determine the characteristics of the file descriptor. You can find information about which flags can be manipulated by reading (or rather) information on <fcntl.h> . Flags include:

  • O_APPEND - setting the add mode.
  • O_DSYNC - record in accordance with the synchronization of the integrity of the input-output data.
  • O_NONBLOCK - non-blocking mode.
  • O_RSYNC - Synchronized I / O.
  • O_SYNC - record in accordance with the completion of the integrity of the synchronized I / O file.

Plus (POSIX 2008) O_ACCMODE, which can then be used to distinguish between O_RDONLY , O_RDWR and O_WRONLY if I read the links correctly.

However, it makes no sense to call fcntl() with a finally 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).

+4
source

Assuming this is a function described by man 2 fcntl :

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

tries to perform some actions with an invalid file descriptor ( -1 ) and therefore never does anything , but returns -1 and sets errno to EBADF .

I would say that you can replace this line as follows:

 flags = -1; errno = EBADF; 
+3
source

The fcntl() function performs various actions on open descriptors. Its syntax is:

 int fcntl(int descriptor, int command, ...) 

read Return value :

  • -1 and then fcntl() failed. The global variable errno is set to indicate an error.

this code:

 #include <sys/types.h> #include <unistd.h> #include <fcntl.h> int main(){ int flags; if((flags = fcntl(-1,F_GETFL,0)) < 0){ perror("fcntl: "); } printf("\n %d\n", flags); } 

:

 ~$ gcc xx.c ~$ ./a.out fcntl: : Bad file descriptor -1 

Note that the printed value of flags is -1 , which indicates a successful call to fcntl(-1,F_GETFL,0); because -1 not a valid file descriptor. And valid file descriptors start at 0 . (this is what perror() prints the error message Bad file descriptor , EBADF)

note: I am running this code on a Linux system.

Edit :
F_GETFL is for the GET flags command in fcntl ().

0
source

Source: https://habr.com/ru/post/945033/


All Articles