Bash.Builtin.Coproc (Bash v0.6.0)

Copy Markdown View Source

coproc [NAME] command [redirections]

Create a coprocess named NAME.

Execute COMMAND asynchronously, with the standard output and standard input of the command connected via a pipe to file descriptors assigned to indices 0 and 1 of an array variable NAME in the executing shell. The default NAME is "COPROC".

The coprocess is executed asynchronously in a subshell, as if the command had been terminated with the & control operator.

When the coprocess is executed, the shell creates an array variable NAME in the context of the executing shell. The standard output of command is connected via a pipe to a file descriptor in the executing shell, and that file descriptor is assigned to NAME[0]. The standard input of command is connected via a pipe to a file descriptor in the executing shell, and that file descriptor is assigned to NAME[1].

The shell also sets the variable NAME_PID to the process ID of the coprocess.

Exit Status: Returns the exit status of COMMAND.

Reference: https://cgit.git.savannah.gnu.org/cgit/bash.git/plain/builtins/reserved.def?h=bash-5.3

Architecture

Two modes of operation:

External (simple commands like coproc cat)

stateDiagram-v2
    [*] --> running: start_link external
    running --> running: read/write via CommandPort
    running --> closing: close_stdin
    closing --> stopped: process exits
    running --> stopped: process exits
    stopped --> [*]

Internal (compound commands like coproc MYPROC { cat; })

stateDiagram-v2
    [*] --> running: start_link internal
    running --> running: read/write via message passing
    running --> closing: close_stdin
    closing --> stopped: body task exits
    running --> stopped: body task exits
    stopped --> [*]

File descriptors stored in the session's file_descriptors map contain {:coproc, pid, :read | :write} tuples that route I/O through this GenServer.