[New-bugs-announce] [issue16860] Use O_CLOEXEC in the tempfile module

STINNER Victor report at bugs.python.org
Fri Jan 4 15:22:29 CET 2013

New submission from STINNER Victor:

os.O_CLOEXEC has been added to Python 3.3. This flag solves a race condition if the process is forked between open() and a call to fcntl() to set the FD_CLOEXEC flag.

The following patch written by neologix should fix this issue:
diff --git a/Lib/tempfile.py b/Lib/tempfile.py
--- a/Lib/tempfile.py
+++ b/Lib/tempfile.py
@@ -57,6 +57,8 @@
 _allocate_lock = _thread.allocate_lock

 _text_openflags = _os.O_RDWR | _os.O_CREAT | _os.O_EXCL
+if hasattr(_os, 'O_CLOEXEC'):
+    _text_openflags |= _os.O_CLOEXEC
 if hasattr(_os, 'O_NOINHERIT'):
     _text_openflags |= _os.O_NOINHERIT
 if hasattr(_os, 'O_NOFOLLOW'):

The patch can be applied to Python 3.3 and 3.4.

components: Library (Lib)
messages: 179023
nosy: haypo, neologix
priority: normal
severity: normal
status: open
title: Use O_CLOEXEC in the tempfile module
versions: Python 3.3, Python 3.4

Python tracker <report at bugs.python.org>

More information about the New-bugs-announce mailing list