This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

Author cptpcrd
Recipients cptpcrd
Date 2020-12-29.17:18:38
SpamBayes Score -1.0
Marked as misclassified Yes
Message-id <>
Note: I filed this bug report after seeing and verifying that it was also reproducible on Python. Credit for discovering the underlying issue should go to Aleksa Sarai, and further discussion can be found there.

# Background

Linux has O_PATH file descriptors. These are file descriptors that refer to a specific path, without allowing any other kind of access to the file. They can't be used to read or write data; instead, they're intended to be used for use cases like the *at() functions. In that respect, they have similar semantics to O_SEARCH on other platforms (except that they also work on other file types, not just directories).

More information on O_PATH file descriptors can be found in open(2) (, or in the Rust PR linked above.

# The problem

As documented in the Rust PR linked above, *no* ioctl() calls will succeed on O_PATH file descriptors (they always fail with EBADF). Since os.set_inheritable() uses ioctl(FIOCLEX)/ioctl(FIONCLEX), it will fail on O_PATH file descriptors.

This is easy to reproduce:

>>> import os
>>> a ="/", os.O_RDONLY)
>>> b ="/", os.O_PATH)
>>> os.set_inheritable(a, True)
>>> os.set_inheritable(b, True)  # Should succeed!
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
OSError: [Errno 9] Bad file descriptor

I believe this affects all versions of Python going back to version 3.4 (where os.set_inheritable()/os.get_inheritable() were introduced).

# Possible fixes

I see two potential paths for fixing this:

1. Don't use ioctl(FIOCLEX) at all on Linux.

This is what Rust did. However, based on bpo-22258 I'm guessing there would be opposition to implementing this strategy in Python, on the grounds that the fcntl() route takes an extra syscall (which is fair).

2. On Linux, fall back on fcntl() if ioctl(FIOCLEX) fails with EBADF.

This could be a very simple patch to Python/fileutils.c. I've attached a basic version of said patch (not sure if it matches standard coding conventions).

Downsides: This would add 2 extra syscalls for O_PATH file descriptors, and 1 extra syscall for actual cases of invalid file descriptors (i.e. EBADF). However, I believe these are edge cases that shouldn't come up frequently.
Date User Action Args
2020-12-29 17:18:38cptpcrdsetrecipients: + cptpcrd
2020-12-29 17:18:38cptpcrdsetmessageid: <>
2020-12-29 17:18:38cptpcrdlinkissue42780 messages
2020-12-29 17:18:38cptpcrdcreate