Hello. As I understand it in the C language, a non-negative number is assigned to each I / O stream - a descriptor. I would like to understand how it is used to identify the stream and what will happen in the course of the program if for some pointer to FILE change its field _file (descriptor). Thanks in advance.

  • 2
    Handles are issued by the operating system kernel. on it, the kernel finds the necessary info in its tables. if _file changes, then of course it will be transferred there on the next calls to the kernel functions and the kernel will try to work with another file - Mike

1 answer 1

As I understand it in the C language, a non-negative number is assigned to each I / O stream - a descriptor.

This is not in C. This is in OS * NIX. In fact, this number is not a descriptor, but a pointer to a file descriptor. More precisely, the index in the file descriptor table maintained by the OS. The first three positions in this table are always occupied:

  • 0 - stdin
  • 1 - stdout
  • 2 - stderr

In the descriptor itself there is a field pointing to a specific file. By writing some value in this field, we can redirect the input / output to another file, as is done with the help of the '>' and '<' characters in the command line.

Beginning with No. 3, file descriptors have no fixed meaning. They are associated with specific files depending on incoming open () / close () calls.

In order to program I / O redirection, you can use the freopen function.

Attempting "on meat" to replace the file descriptor is unlikely to end with something good ...

  • one
    The first three positions in this table are always occupied and this is fundamentally wrong :) They are associated with specific files and again wrong. - KoVadim
  • this is fundamentally wrong :) - Having said "A", it would be nice to say "B" ... Even if I write a demon that completely disconnects from the terminal, then all the same, the "zero" descriptor will be the stdin descriptor. Just there it will be written that it is disabled. But NEVER in the descriptor "zero" will not be located the description of the file opened in the application program, on the call open (). - Sergey
  • one
    if the handle is closed, then the next open can use this handle. According to the second statement, a socket or a pipe can also be hidden behind the descriptor. - KoVadim
  • And besides this, you can simply rebuild libraries with redefined numbers (there will be fun!). - 0andriy
  • if the handle is closed, then the next open can use this handle. - Have you read my answer? It describes this situation. The stdin, stdout, and stderr descriptors are NOT covered by this rule. - Sergey