21.1 Opening file descriptors

Function: mbfl_fd_open_input FD FILE

Open the file descriptor FD to read from FILE. When successful: return true; otherwise return false.

NOTE When FILE is a FIFO: we need to call mbfl_fd_open_input_output(), not this function.

If the predefined options --test or --show-program are enabled: print a line on the standard error channel describing the operation. If the predefined option --test is enabled: the file descriptor is still opened. Predefined options.

Function: mbfl_fd_open_output FD FILE

Open the file descriptor FD to write to FILE. When successful: return true; otherwise return false.

If the predefined options --test or --show-program are enabled: print a line on the standard error channel describing the operation. If the predefined option --test is enabled: the file descriptor is still opened. Predefined options.

Function: mbfl_fd_open_input_output FD FILE

Open the file descriptor FD to read from and write to FILE. When successful: return true; otherwise return false.

If the predefined options --test or --show-program are enabled: print a line on the standard error channel describing the operation. If the predefined option --test is enabled: the file descriptor is still opened. Predefined options.

Let’s see how we can open a file for reading and writing with two file descriptors:

declare TESTFILE=/path/to/file.ext
declare INFD=3 OUFD=4
declare LINE

mbfl_fd_open_output $OUFD "$TESTFILE"
echo 1234 >&${OUFD}
mbfl_fd_close $OUFD

mbfl_fd_open_input  $INFD "$TESTFILE"
read -u ${INFD} LINE
mbfl_fd_close $INFD

echo "$LINE"

now let’s use a location to automatically close the file descriptors:

declare TESTFILE=/path/to/file.ext
declare INFD=3 OUFD=4
declare LINE

mbfl_location_enter
{
    mbfl_fd_open_output $OUFD "$TESTFILE"
    mbfl_location_handler "mbfl_fd_close ${OUFD}"
    echo 1234 >&${OUFD}

    mbfl_fd_open_input  $INFD "$TESTFILE"
    mbfl_location_handler "mbfl_fd_close ${INFD}"
    read -u ${INFD} LINE

    echo "$LINE"
}
mbfl_location_leave

Let’s see how we can use a FIFO for reading and writing with two file descriptors:

mbfl_declare_program mkfifo
mbfl_file_enable_remove

function program_mkfifo () {
    local PATHNAME=${1:?}
    shift 1
    local MKFIFO
    mbfl_program_found_var MKFIFO mkfifo || exit_because_program_not_found

    "$MKFIFO" --mode=0600 "$@" "$PATHNAME"
}

declare TESTFILE=/path/to/fifo.ext
declare INFD=3 OUFD=4
declare LINE

mbfl_location_enter
{
    program_mkfifo "$TESTFIFO"
    mbfl_location_handler "mbfl_file_remove ${TESTFIFO}"

    mbfl_fd_open_input_output $INFD "$TESTFIFO"
    mbfl_location_handler "mbfl_fd_close ${INFD}"

    mbfl_fd_open_output $OUFD "$TESTFIFO"
    mbfl_location_handler "mbfl_fd_close ${OUFD}"

    echo 1234 >&${OUFD}
    read -u ${INFD} LINE

    echo "$LINE"
}
mbfl_location_leave

This document describes version 3.0.0-devel.9 of Marcos Bash Functions Library.