Skip to content

Commit c2bd55d

Browse files
author
Alexey Izbyshev
authored
gh-102179: Fix os.dup2 error reporting for negative fds (#102180)
1 parent 705487c commit c2bd55d

File tree

3 files changed

+21
-5
lines changed

3 files changed

+21
-5
lines changed

Lib/test/test_os.py

+20
Original file line numberDiff line numberDiff line change
@@ -2221,6 +2221,26 @@ def test_closerange(self):
22212221
def test_dup2(self):
22222222
self.check(os.dup2, 20)
22232223

2224+
@unittest.skipUnless(hasattr(os, 'dup2'), 'test needs os.dup2()')
2225+
@unittest.skipIf(
2226+
support.is_emscripten,
2227+
"dup2() with negative fds is broken on Emscripten (see gh-102179)"
2228+
)
2229+
def test_dup2_negative_fd(self):
2230+
valid_fd = os.open(__file__, os.O_RDONLY)
2231+
self.addCleanup(os.close, valid_fd)
2232+
fds = [
2233+
valid_fd,
2234+
-1,
2235+
-2**31,
2236+
]
2237+
for fd, fd2 in itertools.product(fds, repeat=2):
2238+
if fd != fd2:
2239+
with self.subTest(fd=fd, fd2=fd2):
2240+
with self.assertRaises(OSError) as ctx:
2241+
os.dup2(fd, fd2)
2242+
self.assertEqual(ctx.exception.errno, errno.EBADF)
2243+
22242244
@unittest.skipUnless(hasattr(os, 'fchmod'), 'test needs os.fchmod()')
22252245
def test_fchmod(self):
22262246
self.check(os.fchmod, 0)
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Fix :func:`os.dup2` error message for negative fds.

Modules/posixmodule.c

-5
Original file line numberDiff line numberDiff line change
@@ -9795,11 +9795,6 @@ os_dup2_impl(PyObject *module, int fd, int fd2, int inheritable)
97959795
static int dup3_works = -1;
97969796
#endif
97979797

9798-
if (fd < 0 || fd2 < 0) {
9799-
posix_error();
9800-
return -1;
9801-
}
9802-
98039798
/* dup2() can fail with EINTR if the target FD is already open, because it
98049799
* then has to be closed. See os_close_impl() for why we don't handle EINTR
98059800
* upon close(), and therefore below.

0 commit comments

Comments
 (0)