Home > database >  Error "write(stdout): Broken pipe" when using GNU netcat with named pipe
Error "write(stdout): Broken pipe" when using GNU netcat with named pipe

Time:07-22

I have a simple shell script sv that responds to HTTP requests with a short message:

#!/bin/sh

echo_crlf() {
        printf '%s\r\n' "$@"
}

respond() {
        body='Hello world!'
        echo_crlf 'HTTP/1.1 200 OK'
        echo_crlf 'Connection: close'
        echo_crlf "Content-Length: $(echo "$body" | wc -c)"
        echo_crlf 'Content-Type: text/plain'
        echo_crlf
        echo "$body"
}

mkfifo tube
respond < tube | netcat -l -p 8888 > tube
rm tube

When I start the script and send a request, everything looks right on the client side:

$ ./sv

$ curl localhost:8888
Hello world!
$

but the script prints the following error:

$ ./sv
write(stdout): Broken pipe
$

I am running this script on Linux, using GNU's implementation of netcat and coreutils. I've tried running this script with both dash and bash; the same error occurs.

What is the cause of this error and how can I avoid it?


Edit: It seems that the error was caused by leaving out the read command in respond in simplifying my code for this question. That or the lack of a Connection: close header when testing with a web browser causes this error message.

CodePudding user response:

You're writing to the FIFO "tube" but no one is reading from it. You can try like this:

{ respond; cat tube > /dev/null; } | netcat -l -p 8888 > tube

I don't get the point of using the FIFO here. The following would just work:

respond | netcat -l -p 8888 > /dev/null
  • Related