Index: Lib/test/test_fileio.py =================================================================== --- Lib/test/test_fileio.py (revision 68737) +++ Lib/test/test_fileio.py (working copy) @@ -176,6 +176,10 @@ f.close() os.unlink(TESTFN) + def testInvalidFd(self): + self.assertRaises(ValueError, _fileio._FileIO, -10) + self.assertRaises(OSError, _fileio._FileIO, 10) + def testBadModeArgument(self): # verify that we get a sensible error message for bad mode argument bad_mode = "qwerty" Index: Modules/_fileio.c =================================================================== --- Modules/_fileio.c (revision 68737) +++ Modules/_fileio.c (working copy) @@ -119,7 +119,25 @@ return 0; } +static int +check_fd(int fd) +{ +#if defined(HAVE_FSTAT) && defined(EBADF) + struct stat buf; + if (fstat(fd, &buf) < 0 && errno == EBADF) { + PyObject *exc; + char *msg = strerror(EBADF); + exc = PyObject_CallFunction(PyExc_OSError, "(is)", + EBADF, msg); + PyErr_SetObject(PyExc_OSError, exc); + Py_XDECREF(exc); + return -1; + } +#endif + return 0; +} + static int fileio_init(PyObject *oself, PyObject *args, PyObject *kwds) { @@ -151,6 +169,8 @@ "Negative filedescriptor"); return -1; } + if (check_fd(fd)) + return -1; } else { PyErr_Clear();