Monday, May 18, 2009

Bash - Asynchronous Write/Read to FIFO files

This might be useful where you have a case where one process writes to a pipe and leaves, another process then reads from it later on.

FIFO_FILE="/tmp/pipefile";

# Create and Set OUTPUT File Descriptor for reading
set_output_fd () {
# Assigning file descriptor 3 to the pipe
exec 3> $FIFO_FILE || {
echo "$(basename $0): error creating named pipe. Exiting." >&2;
exit 2;
}
}

# Close Pipe/FIFO
close_output_fd () {
exec 3>&-;
}

You may now simply call the functions as:
set_output_fd;

# Write
echo "Writing to pipe..." 2>&3;

# Read
echo "Reading data from pipe: " `/bin/cat $FIFO_FILE`;

close_output_fd;

No comments:

Post a Comment