Attached patch is avoids a syscall in os.set_inheritable() if the FD_CLOEXEC flag is already set/cleared. The change only impacts platforms using fcntl() in _Py_set_inheritable(). Windows has a different implementation, and Linux uses ioctl() for example. The same "optimization" is used in socket.socket.setblocking(): see the issue #19827.
> Another question: should we handle EINTR in ioctl() and fcntl()? But this is a different issue. See attached test stress.py. I tried it with ioctl() and fcntl() implementations of os.set_inheritable() and I got more than 10,000 signals: no syscalls failed with EINTR. IMHO EINTR is only used when the syscall waits, for example wait for I/O. I don't think that setting FD_CLOEXEC requires any I/O. Example: $ ./python stress.py got 16871 signals