Issue 1422: Writing to an invalid fd doesn't raise an exception (original) (raw)

The bug is related to http://bugs.python.org/issue1415 and occurs only with the latest patch from #1415.

Writing to an invalid fd doesn't raise an exception:

f = open(100, 'w') f.fileno() 100 f.write("test") 4

However reading or opening an invalid fd for reading and writing raises an exception.

f = open(100, 'r') f.read() Traceback (most recent call last): File "", line 1, in File "/home/heimes/dev/python/py3k/Lib/io.py", line 1253, in read res += decoder.decode(self.buffer.read(), True) File "/home/heimes/dev/python/py3k/Lib/io.py", line 756, in read current = self.raw.read(to_read) IOError: [Errno 9] Bad file descriptor f = open(100, 'w+') Traceback (most recent call last): File "", line 1, in File "/home/heimes/dev/python/py3k/Lib/io.py", line 195, in new return open(*args, **kwargs) File "/home/heimes/dev/python/py3k/Lib/io.py", line 169, in open buffer = BufferedRandom(raw, buffering) File "/home/heimes/dev/python/py3k/Lib/io.py", line 948, in init raw._checkSeekable() File "/home/heimes/dev/python/py3k/Lib/io.py", line 301, in _checkSeekable if msg is None else msg) IOError: File or stream is not seekable.

I expected that fileio_write() raises an exception when fd is invalid:

    n = write(self->fd, ptr, n);
    if (n < 0) {
            if (errno == EAGAIN)
                    Py_RETURN_NONE;
            PyErr_SetFromErrno(PyExc_IOError);
            return NULL;
    }

Python 2.5 and probably 2.6 suffer from the same problem although it's harder to trigger it.

Python 2.5.1 (r251:54863, Oct 5 2007, 13:36:32) [GCC 4.1.3 20070929 (prerelease) (Ubuntu 4.1.2-16ubuntu2)] on linux2 Type "help", "copyright", "credits" or "license" for more information.

import os f = open("/tmp/test", 'w') f.fileno() 3 os.close(f.fileno()) f.write("test") f.write("test")

close failed: [Errno 9] Bad file descriptor $ ls -la /tmp/test -rw-r----- 1 heimes heimes 0 2007-11-11 20:46 /tmp/test

I don't think this is worth fixing; you'll get an I/O error as soon as I/O is attempted, which is upon the first read() for input, or upon the firsh (implicit or explicit) flush() on output. You can't tell whether a fd is valid or not without attempting I/O on it, so trying to test on each write() call would defeat the purpose of buffering. Testing on open() is insufficient as long as anybody could call os.close() any time.