Search code examples
pythonfile-descriptortemporary-files

Why is the automatically generated file descriptor starting at 3?


Are the file descriptors with a lower value opened for a different process, if so which, or is this just a convention?

See the following interpreter session below, executed in Ubuntu20.04 on WSL2:

Python 3.8.2 (default, Jul 16 2020, 14:00:26)
[GCC 9.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> import tempfile
>>>
>>> fd, path_3 = tempfile.mkstemp()
>>> print(fd, path_3)
3 /tmp/tmpeaqkgmmg
>>>
>>> fd, path_4 = tempfile.mkstemp()
>>> print(fd, path_4)
4 /tmp/tmp3tskrarr
>>>
>>> os.close(3)
>>> os.unlink(path_3)
>>>
>>> os.close(4)
>>> os.unlink(path_4)
>>>
>>> fd, path_3 = tempfile.mkstemp()
>>> print(fd, path_3)
3 /tmp/tmpsyqvut1r

From the above session is clear that when the file descriptor is not in use anymore, the mkstemp automatically selects the lowest number available. So, what about 0, 1 and 2?


Solution

  • 0, 1 and 2 are file descriptors linked with the standard input, output and error respectively. Every process in a POSIX compliant system should have them. You can see this as a direct consequence of the "everything is a file" philosophy: input is like a file you can read from and output is like a file you can write to.

    As Tryph mentioned in the comments, you may read the wiki article on file descriptors for more information.