5

I have read that $coproc < command > is different from $< command > & in that coproc will execute command in a sub-shell process.

But when I tested it, it worked just like $< command > &. The test is as follow:

First: test the behavior of $< command > &.

  1. Run $nano & on tty1
  2. On another tty, output from $ps -t tty1 --forest indicates nano process is child process of the -bash process (login bash shell process -> no sub-shell process was created)

Second: test the behavior of $coproc < command >

  1. Run $coproc nano on tty1
  2. On another tty, output from $ps -t tty1 --forest is the same as above (no sub-shell process was created)

So is $coproc < command > simply the same as $< command > &?

The shell used was a bash shell

2 Answers2

4

coproc utility is not the same as utility & in bash.

With coproc utility you get an array, COPROC, that contains the standard input and output filedescriptors of utility. You may then do things like

#!/bin/bash

coproc bc -l

for (( k = 0; k < 50; ++k )); do
  printf '2.3*%d + 1\n' "$k" >&${COPROC[1]}
  read -u "${COPROC[0]}" a
  printf '%.2f\n' "$a"
done

kill "$COPROC_PID"

Here, bc -l is a co-process and acts like a "arithmetic computation service" for the shell loop, taking expressions to compute on its standard input and giving back results on its standard output.

As far as I can tell, bash also only supports one co-process at any one time.

The ksh93 shell also supports co-processes, but the syntax is totally different (but somewhat sleeker). This is the equivalent ksh93 script:

#!/usr/bin/ksh93

bc -l |&
coproc_pid=$!

for (( k = 0; k < 50; ++k )); do
  print -p -f '2.3*%d + 1\n' "$k"
  read -p a
  printf '%.2f\n' "$a"
done

kill "$coproc_pid"

Here, it's the -p option to print and read that makes it communicate with the co-process (the process started with |&) rather than using some explicit filedescriptor.

Kusalananda
  • 333,661
  • I am still investigating your answer, but just to make it clear, so the difference between coproc and `&' in bash isn't the creation of a sub-shell process? – Tran Triet Oct 02 '18 at 07:24
2

The difference is the creation of two I/O channels, as described in man bash:

A coprocess is executed asynchronously in a subshell, as if the command had been terminated with the & control operator, with a two-way pipe established between the executing shell and the coprocess.

RudiC
  • 8,969