What are the possible values ​​for file descriptors?

I am interested in knowing the valid values ​​that I can expect for a file descriptor.

Please let me clarify a bit. I know that, for example, when I use #include <unistd.h> on my Linux system, then opening the file for reading is called:

 int fileDescriptor; fileDescriptor = open("/some/filename",O_RDONLY); 

an error may occur and as a result I get -1.
Accidentally (- 1) the negative must have some special meaning. Is all the other values ​​valid file descriptors? i.e. negative like -2 and -1023?

Assuming int is 4 bytes ( sizeof(int)==4 ), then <

 (-1) = 10000000 0000000 00000000 00000001 

will be the only detectable invalid file descriptor? Others would like to:

  • (0) = 00000000 0000000 00000000 00000000
  • (-2) = 10000000 0000000 00000000 00000010
  • (2) = 00000000 0000000 00000000 00000010

to be okay? Since a file descriptor can store 4 bytes, I could have a maximum (2 ^ (8 * 4) -1) of valid file descriptors, and therefore this would be the maximum number of files that I can open, right?

Repeat again:

What should I expect a (valid) file descriptor?

any value but -1?

+7
c linux validation file-descriptor
source share
4 answers

On the page :

open() returns a file descriptor, a small, non-negative integer .

and then:

open() and creat() return a new file descriptor or -1 if an error occurred

+12
source share

If open does not work, it returns -1 or 0xffffffff . It doesn't matter, but open failed:

After successful completion, the function should open the file and return a non-negative integer representing the smallest number of unused file descriptor. Otherwise -1 is returned and errno is set to indicate an error. No files should be created or modified if the function returns -1.

The reason for the failure is stored in errno , you can read its meaning and check if this is one of the possible reasons for the failure of EACCES , EEXIST , EINTR , etc. or just use perror to print an error message.

+2
source share

Here on the Linux man page says:

open() and creat() return a new file descriptor or -1 if an error occurred (in this case errno set accordingly).

Other systems may return other negative values ​​in the event of an error.

+1
source share

The range of possible file descriptor values ​​is from 0 to 1023 for a Linux system (32-bit or 64-bit).

You cannot create a file descriptor with a value greater than 1023. In the case of a file descriptor of value 1024, it will return an EBADF error (bad file descriptor, error No. 9).

When a negative file descriptor value is returned, this indicates that an error has occurred.

+1
source share

All Articles