Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to flush a pipe using bash

I have a script that writes to a named pipe and another that reads from the pipe. Occasionally, when starting the script I have noticed that the contents of the pipe exist from a previous run of the script. Is there a way to flush out the pipe at the beginning of the script?

like image 470
User1 Avatar asked Jul 27 '10 22:07

User1


People also ask

What does [- Z $1 mean in bash?

$1 means an input argument and -z means non-defined or empty. You're testing whether an input argument to the script was defined when running the script. Follow this answer to receive notifications.

What is the pipe command in bash?

A pipe in Bash takes the standard outputstandard outputStandard output (stdout) Standard output is a stream to which a program writes its output data. The program requests data transfer with the write operation. Not all programs generate output.https://en.wikipedia.org › wiki › Standard_streamsStandard streams - Wikipedia of one process and passes it as standard input into another process. Bash scripts support positional arguments that can be passed in at the command line.

What is $s in bash?

From man bash : -s If the -s option is present, or if no arguments remain after option processing, then commands are read from the standard input. This option allows the positional parameters to be set when invoking an interactive shell. From help set : -e Exit immediately if a command exits with a non-zero status.


2 Answers

I think dd is your friend:

dd if=myfifo iflag=nonblock of=/dev/null

strace shows

open("myfifo", O_RDONLY|O_NONBLOCK)

and indeed doesn't even block on an empty fifo.

like image 189
mvds Avatar answered Oct 13 '22 12:10

mvds


You can read from the pipe until it is empty. This will effectively flush it.

Before you attempt this daring feat, call fcntl(mypipe, F_SETFL, O_NONBLOCK) (I don't know the shell-scripting equivalent) to make a read when the pipe is empty not hang your program.

like image 39
Borealid Avatar answered Oct 13 '22 13:10

Borealid