在Python中,fcntl
模塊用于文件描述符的控制操作
import os
import fcntl
def set_nonblocking(file_descriptor):
try:
flags = fcntl.fcntl(file_descriptor, fcntl.F_GETFL)
fcntl.fcntl(file_descriptor, fcntl.F_SETFL, flags | os.O_NONBLOCK)
except IOError as e:
print(f"Error setting file descriptor to non-blocking: {e}")
return False
return True
def is_nonblocking(file_descriptor):
try:
flags = fcntl.fcntl(file_descriptor, fcntl.F_GETFL)
return flags & os.O_NONBLOCK != 0
except IOError as e:
print(f"Error checking if file descriptor is non-blocking: {e}")
return False
# Example usage
file_descriptor = os.open("example.txt", os.O_RDONLY)
if set_nonblocking(file_descriptor):
print("File descriptor set to non-blocking")
else:
print("Failed to set file descriptor to non-blocking")
if is_nonblocking(file_descriptor):
print("File descriptor is non-blocking")
else:
print("File descriptor is not non-blocking")
os.close(file_descriptor)
在這個示例中,我們定義了兩個函數:set_nonblocking
和is_nonblocking
。這兩個函數都使用了try-except
語句來捕獲可能的IOError
異常,并在發生異常時打印錯誤消息。這樣,我們可以簡化錯誤處理并確保在出現問題時能夠給出有關錯誤的詳細信息。