20.16.2 Redirection of standard channels to FIFO pathnames

Another way is to generate unique file pathnames for 2 named pipes and, somehow, launch the processes redirecting their standard input and output channels to the appropriate named pipes. Let’s say a parent process executes a child process with mbfl_program_execbg().

The parent can look like this:

mbfl_file_enable_remove
mbfl_process_enable

function doit () {
    declare -r CHILD=/path/to/child.bash

    declare -r FIFO_PARENT_TO_CHILD=/path/to/fifo-parent-to-child.$RANDOM
    declare -r FIFO_CHILD_TO_PARENT=/path/to/fifo-child-to-parent.$RANDOM

    declare -ri FD_PARENT_TO_CHILD=4
    declare -ri FD_CHILD_TO_PARENT=5

    mbfl_location_enter
    {
        mbfl_declare_varref(OUTER_HOOK)
        mbfl_location_hook_var _(OUTER_HOOK)

        sub_doit

        printf 'ciao child\n' >&$FD_PARENT_TO_CHILD
        read -u $FD_CHILD_TO_PARENT
    }
    mbfl_location_leave
}
function sub_doit () {
    mbfl_location_enter
    {
        if mbfl_exec_mkfifo --mode=0600 -- "$FIFO_PARENT_TO_CHILD"
        then mbfl_location_handler "mbfl_file_remove '$FIFO_PARENT_TO_CHILD'"
        else
            mbfl_location_leave
            return_failure
        fi

        if mbfl_exec_mkfifo --mode=0600 -- "$FIFO_CHILD_TO_PARENT"
        then mbfl_location_handler "mbfl_file_remove '$FIFO_CHILD_TO_PARENT'"
        else
            mbfl_location_leave
            return_failure
        fi

        if mbfl_fd_open_input_output $FD_PARENT_TO_CHILD "$FIFO_PARENT_TO_CHILD"
        then mbfl_hook_add $OUTER_HOOK "mbfl_fd_close $FD_PARENT_TO_CHILD"
        else
            mbfl_location_leave
            return_failure
        fi

        if mbfl_fd_open_input_output $FD_CHILD_TO_PARENT "$FIFO_CHILD_TO_PARENT"
        then mbfl_hook_add $OUTER_HOOK "mbfl_fd_close $FD_CHILD_TO_PARENT"
        else
            mbfl_location_leave
            return_failure
        fi

        if mbfl_program_execbg $FD_PARENT_TO_CHILD $FD_CHILD_TO_PARENT "$mbfl_PROGRAM_BASH" "$CHILD"
        then mbfl_hook_add $OUTER_HOOK "mbfl_process_wait $mbfl_program_BGPID"
        else
            mbfl_location_leave
            return_failure
        fi

        # We have connected  both the ends of  both the FIFOs, so  we can remove them  from the file
        # system: the FIFOs will continue to exist until the file descriptors are closed.
    }
    mbfl_location_leave
}

The child can look like this:

function main () {
  read
  printf 'ciao parent\n'
}

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