Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

does closing a file opened with os.fdopen close the os-level fd?

I'm making a temporary file with tempfile.mkstemp(). It returns an os-level fd along with the path to the file. I want to os.fdopen() the os-level file descriptor to write to it. If I then close the file that os.fdopen() returned, will the os-level file descriptor be closed, or do I have to os.close() it explicitly? The docs don't seem to say what happens explicitly.

like image 884
Claudiu Avatar asked Aug 18 '11 20:08

Claudiu


People also ask

How do you close after Fdopen?

If fdopen() returns NULL, use close() to close the file. If fdopen() is successful, you must use fclose() to close the stream and file.

What is fdopen in Python?

fdopen() takes an existing file descriptor and builds a Python file object around it. It converts a file descriptor to a full file object. It is useful when interfacing with C code or with APIs that only create low-level file descriptors.

What is OS close in Python?

close() method in Python is used to close the given file descriptor, so that it no longer refers to any file or other resource and may be reused. A file descriptor is small integer value that corresponds to a file or other input/output resource, such as a pipe or network socket.

What is FD function in Python?

fd − This is the file descriptor for which a file object is to be returned. mode − This optional argument is a string indicating how the file is to be opened. The most commonly-used values of mode are 'r' for reading, 'w' for writing (truncating the file if it already exists), and 'a' for appending.


1 Answers

I'm pretty sure the fd will be closed. If you don't want that you can dup it first. Of course you can always test this easily enough.

Test is like this:

from __future__ import print_function

import os
import tempfile
import errno

fd, tmpname = tempfile.mkstemp()
fo = os.fdopen(fd, "w")
fo.write("something\n")
fo.close()
try:
    os.close(fd)
except OSError as oserr:
    if oserr.args[0] == errno.EBADF:
            print ("Closing file has closed file descriptor.")
    else:
        print ("Some other error:", oserr)
else:
    print ("File descriptor not closed.")

Which shows that the underlying file descriptor is closed when the file object is closed.

like image 99
Keith Avatar answered Oct 19 '22 17:10

Keith