Named pipe getting "clogged"

for elem in {1..99} ; do echo $elem> mypipe ; done

This piece of bash code should pass 99 ints through the pipe, which previously, in another terminal had this set:

cat <mypipe

Does anyone know why I'm sometimes only getting a random (less than 99) number of ints passed through the pipe, after which it hangs? I have to terminate the script with Ctrl+c, and I get this message:

bash: mypipe: Interrupted system call

I am running Ubuntu 11.10.

1 Answer

The problem with your code is that > mypipe will open the fifo, write to it, then close it. Once it's closed in either end, you have to reopen it in both ends. So instead of reopening the fifo for every echo, keep it open for the entire loop.

for elem in {1..99}; do echo "$elem"; done > mypipe

Btw, in place of that for loop, you could just use a single printf

printf '%s\n' {1..99} > mypipe

If you have a more complex case. You can assign an fd to it instead.

exec 3> mypipe # opens mypipe for writing on fd 3
echo "stuff" >&3
echo "more stuff" >&3
...
exec 3>&- # closes fd 3

See for more.

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like