Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

flags = fcntl(-1,F_GETFL,0);
like image 240
42_huh Avatar asked May 15 '13 04:05

42_huh


People also ask

What is Fcntl function What is the purpose of using it?

The fcntl is a system call. It allows the program to place a read or a write lock. This function can be used to amend the file properties that are either opened already or can be opened through any action applied to it. It is a versatile function and is used to modify files in many ways like open, read and write, etc.

What is fcntl ()?

The fcntl() function provides for control over open files. The fildes argument is a file descriptor. The available values for cmd are defined in the header <fcntl.

What is O_ndelay?

If O_NDELAY or O_NONBLOCK is set: The open will return without waiting for the device to be ready or available; subsequent behavior of the device is device specific. If O_NDELAY and O_NONBLOCK are clear: The open will block until the device is ready or available.

What is O_nonblock?

Macro: int O_NONBLOCK. This prevents open from blocking for a “long time” to open the file. This is only meaningful for some kinds of files, usually devices such as serial ports; when it is not meaningful, it is harmless and ignored.


2 Answers

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

like image 61
Jonathan Leffler Avatar answered Oct 14 '22 15:10

Jonathan Leffler


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;
like image 35
alk Avatar answered Oct 14 '22 14:10

alk