Skip to content

Commit 7158949

Browse files
miss-islingtonZackerySpytz
authored andcommitted
bpo-37267: Do not check for FILE_TYPE_CHAR in os.dup() on Windows (GH-14051) (GH-14141)
On Windows, os.dup() no longer creates an inheritable fd when handling a character file. (cherry picked from commit 28fca0c) Co-authored-by: Zackery Spytz <zspytz@gmail.com>
1 parent 351b0e7 commit 7158949

3 files changed

Lines changed: 16 additions & 12 deletions

File tree

Lib/test/test_os.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3240,6 +3240,15 @@ def test_dup(self):
32403240
self.addCleanup(os.close, fd2)
32413241
self.assertEqual(os.get_inheritable(fd2), False)
32423242

3243+
@unittest.skipUnless(sys.platform == 'win32', 'win32-specific test')
3244+
def test_dup_nul(self):
3245+
# os.dup() was creating inheritable fds for character files.
3246+
fd1 = os.open('NUL', os.O_RDONLY)
3247+
self.addCleanup(os.close, fd1)
3248+
fd2 = os.dup(fd1)
3249+
self.addCleanup(os.close, fd2)
3250+
self.assertFalse(os.get_inheritable(fd2))
3251+
32433252
@unittest.skipUnless(hasattr(os, 'dup2'), "need os.dup2()")
32443253
def test_dup2(self):
32453254
fd = os.open(__file__, os.O_RDONLY)
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
On Windows, :func:`os.dup` no longer creates an inheritable fd when handling
2+
a character file.

Python/fileutils.c

Lines changed: 5 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1659,7 +1659,6 @@ _Py_dup(int fd)
16591659
{
16601660
#ifdef MS_WINDOWS
16611661
HANDLE handle;
1662-
DWORD ftype;
16631662
#endif
16641663

16651664
assert(PyGILState_Check());
@@ -1673,9 +1672,6 @@ _Py_dup(int fd)
16731672
return -1;
16741673
}
16751674

1676-
/* get the file type, ignore the error if it failed */
1677-
ftype = GetFileType(handle);
1678-
16791675
Py_BEGIN_ALLOW_THREADS
16801676
_Py_BEGIN_SUPPRESS_IPH
16811677
fd = dup(fd);
@@ -1686,14 +1682,11 @@ _Py_dup(int fd)
16861682
return -1;
16871683
}
16881684

1689-
/* Character files like console cannot be make non-inheritable */
1690-
if (ftype != FILE_TYPE_CHAR) {
1691-
if (_Py_set_inheritable(fd, 0, NULL) < 0) {
1692-
_Py_BEGIN_SUPPRESS_IPH
1693-
close(fd);
1694-
_Py_END_SUPPRESS_IPH
1695-
return -1;
1696-
}
1685+
if (_Py_set_inheritable(fd, 0, NULL) < 0) {
1686+
_Py_BEGIN_SUPPRESS_IPH
1687+
close(fd);
1688+
_Py_END_SUPPRESS_IPH
1689+
return -1;
16971690
}
16981691
#elif defined(HAVE_FCNTL_H) && defined(F_DUPFD_CLOEXEC)
16991692
Py_BEGIN_ALLOW_THREADS

0 commit comments

Comments
 (0)