How to close a range of file descriptors in Python

What are file descriptors in Linux?

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.

  • Standard Input (STDIN) with the file descriptor as 0.
  • Standard Output (STDOUT) with the file descriptor as 1.
  • Standard Error (STDERR) with the file descriptor as 2.

The os module

The os module in Python provides functions that help us interact with the underlying operating system.

The closerange method of the os module

The 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.

Syntax

os.closerange(fd_low, fd_high)

Parameter

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).

Example

main.py
file.txt
import socket, os
f_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)

Explanation

  • Line 1: We import the os and socket.
  • Lines 3–5: We obtain the file descriptor for the file file.txt.
  • Line 7: We create a TCP socket.
  • Line 8: We create UDP socket.
  • Line 10: We obtain the file descriptor for the TCP socket.
  • Line 11: We obtain the file descriptor for the UDP socket.
  • Lines 13–15: We print the file descriptor of the file.txt, TCP, and UDP sockets.
  • Line 18: We use the closerange() method to close all the file descriptors using the.