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

3

7

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

flags = fcntl(-1,F_GETFL,0);
Completion answered 15/5, 2013 at 4:58 Comment(0)
P
4

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).

Psychoneurotic answered 15/5, 2013 at 6:16 Comment(0)
B
3

Assuming we are talking about the function described by man 2 fcntl:

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

tries to perform some action on an invalid file descriptor (-1) and therefore will never do anything else but returning -1 and set errno to EBADF.

I'd say you can savely replace this line by:

flags = -1; errno = EBADF;
Bronder answered 15/5, 2013 at 7:8 Comment(0)
C
0

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

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

read about Return Value:

  • -1 then fcntl() was not successful. The errno global variable is set to indicate the 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);
}

output is:

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

 -1

Notice the printed flags value is -1 that indicates not successful call of fcntl(-1,F_GETFL,0); because -1 is not a valid file descriptor. And valid file descriptors starts from 0. (that is what perror() prints error message Bad file descriptor, EBADF)

note: I run this code in Linux System.

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

Congratulatory answered 15/5, 2013 at 5:40 Comment(1)
So the purpose of your code is nothing but shows that -1 is not a valid file descriptor :) , let me know if you need more help on this.Congratulatory

© 2022 - 2024 — McMap. All rights reserved.