Everything is a file in Linux. Files, directories, sockets, etc are all files. Every file has a non-negative integer associated with it. This non-negative integer is called the file descriptor for that particular file. The file descriptors are allocated in sequential order with the lowest possible unallocated positive integer value taking precedence.
Whenever a program is run/executed, the following files are always opened.
0
.1
.2
.os
moduleThe os
module in Python provides functions that help us interact with the underlying operating system.
closerange
method of the os
moduleThe closerange
method of the os
module is used to close all the file descriptors in the given range.
Note: Refer How to close a file descriptor in python? for closing a single file descriptor.
os.closerange(fd_low, fd_high)
The method accepts two parameters i.e fd_low
and fd_high
. The method closes all the file descriptors in the range [fd_low, fd_high)
.
import socket, osf_name = "file.txt"fileObject = open(f_name, "r")fd_fileObject = fileObject.fileno()tcp_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)udp_sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)tcp_sock_fd = tcp_sock.fileno()udp_sock_fd = udp_sock.fileno()print("File descriptor for file.txt is %s" % (fd_fileObject))print("File descriptor for TCP socket is %s" % (tcp_sock_fd))print("File descriptor for UDP socket is %s" % (udp_sock_fd))print("Closing all file descriptors")os.closerange(fd_fileObject, udp_sock_fd + 1)
os
and socket
.file.txt
.file.txt
, TCP, and UDP sockets.closerange()
method to close all the file descriptors using the.