In my case this error was occurring due to multi-threaded accesses to a MCP23S17 I/O expander and an MCP3008 ADC analog to digital converter.
Errors looked like:
File "/home/pi/RWPi/PDALib.py", line 324, in writeDio
r = spi.xfer([0x40,reg,val&255,val>>8])
IOError: [Errno 9] Bad file descriptor
and
File "/home/pi/RWPi/PDALib.py", line 319, in readDio
r = spi.xfer([0x41,reg,0,0])
IOError: [Errno 9] Bad file descriptor
The fix in Python appears to be to use a critical section around the reads and writes:
import threading
dio_lock = threading.Lock() # mutex variable that threads will attempt to grab
def read_something( ):
with dio_lock: # critical section
value=perform function
return value
def write_something( ):
with dio_lock: # critical section
value=perform function
return value
I was running three polling threads - bumpers, ultrasonic distance, and motor control - that were frequently causing the
"IOError: [Errno 9] Bad file descriptor" exceptions.
Since adding the critical section around the reads and writes, I have not seen the error.