Open In App

Python | os.set_blocking() method

Improve
Improve
Like Article
Like
Save
Share
Report

OS module in Python provides functions for interacting with the operating system. OS comes under Python’s standard utility modules. This module provides a portable way of using operating system dependent functionality.

os.set_blocking() method in Python is used to set the blocking mode of the specified file descriptor. This method modifies the os.O_NONBLOCK flag. It sets the os.O_NONBLOCK flag for non-blocking mode and clears the os.O_NONBLOCK flag for blocking mode.

A file descriptor in blocking mode means that I/O system calls like read, write, or connect can be blocked by the system.
For example: If we call read system call on stdin then our program will get blocked (the kernel will put the process into the sleeping state) until data to be read is actually available on stdin.

Note: os.set_blocking() method is available on Unix platforms only.

Syntax: os.set_blocking(fd, blocking)

Parameter:
fd: A file descriptor whose blocking mode is to be set.
blocking: A Boolean value. True if the file descriptor is to be put into blocking mode and false if the file descriptor is to be put into non-blocking mode.

Return Type: This method does not return any value.

Code: Use of os.set_blocking() method to set the blocking mode of a file descriptor.




# Python program to explain os.set_blocking() method 
    
# importing os module 
import os
  
# File path 
path = "/home/ihritik/Documents/file.txt"
  
# Open the file and get
# the file descriptor associated
# with it using os.open() method
fd = os.open(path, os.O_RDWR)
  
  
# Get the current blocking mode
# of the file descriptor
# using os.get_blocking() method
print("Blocking Mode:", os.get_blocking(fd)) 
  
  
# Change the blocking mode
blocking = False
os.set_blocking(fd, blocking)
print("Blocking mode changed")
  
  
# Get the blocking mode
# of the file descriptor
# using os.get_blocking() method
print("Blocking Mode:", os.get_blocking(fd)) 
  
  
# close the file descriptor
os.close(fd)
  
  
# A False value for blocking
# mode denotes that the file
# descriptor has been put into
# Non-Blocking mode while True
# denotes that file descriptor
# is in blocking mode.


Output:

Blocking Mode: True
Blocking mode changed
Blocking Mode: False

Reference: https://docs.python.org/3/library/os.html#os.set_blocking


Last Updated : 18 Jun, 2019
Like Article
Save Article
Share your thoughts in the comments
Similar Reads