I am trying to understand what this line of code means:
flags = fcntl(-1,F_GETFL,0);
I am trying to understand what this line of code means:
flags = fcntl(-1,F_GETFL,0);
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:
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).
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;
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().
© 2022 - 2024 — McMap. All rights reserved.
-1
is not a valid file descriptor :) , let me know if you need more help on this. – Congratulatory