Why does `read` fail saying "read error: 0: Resource temporarily unavailable"?
script
#!/bin/bash --
# record from microphone
rec --channels 1 /tmp/rec.sox trim 0.9 band 4k noiseprof /tmp/noiseprof &&
# convert to mp3
sox /tmp/rec.sox --compression 0.01 /tmp/rec.mp3 trim 0 -0.1 &&
# play recording to test for noise
play /tmp/rec.mp3 &&
printf "nRemove noise? "
read reply
# If there's noise, remove it
if [[ $reply == "y" ]]; then
sox /tmp/rec.sox --compression 0.01 /tmp/rec.mp3 trim 0 -0.1 noisered /tmp/noiseprof 0.1
play /tmp/rec.mp3
fi
Errors with: read error: 0: Resource temporarily unavailable
But, the script works if I use the -e
flag on read
to enable readline
What happens is that one of your SoX programs (sox
, play
, rec
) has changed how stdin
is behaving, making it non-blocking. Typically, something is calling fcntl
(0, F_SETFL, O_NONBLOCK)
.
When a call to the read()
system call is made on a non-blocking file descriptor, the call does not wait: either there is already something to read in the kernel buffer and it is returned, or read()
fails and errno
is set to EAGAIN
.
When Bash meets this EAGAIN
error while reading from stdin with the read
command, it displays the "Resource temporarily unavailable" message you have met.
Try adding <&-
at the end of each of your SoX commands; this will close stdin
for them and they won’t be able to alter how it is working.