How To Do: subprocess in bashscript

How To Do: subprocess in bashscript

Running a co-process in the background can be achieved by using & operator or coproc command. the only difference is that coproc allows to read and send output to the process while & operator doesn't.

(1) using coproc

In Linux coproc command is used to create a co-process or sub process which is connected to the calling process via two pipes, one for sending the input and other for reading the output. the process created here is executed asynchronously within a subshell. the basic syntax is as follows:
coproc [NAME] command [args]

the above syntax has NAME field as optional, but the default NAME field is COPROC and Process Id is given as COPROC_PID

#!/bin/bash
coproc (echo $PWD);
echo "PID : ${COPROC_PID}";
echo ${COPROC[@]};

the above command will result in array of two integers with a read(63) and write(60) discriptors

#OUTPUT 
"PID : 11376"
"63 60"

Read From Co-Process

now lets try to read the output from the above command

#!/bin/bash
coproc (echo $PWD);
echo "PID : ${COPROC_PID}"
read -r out <&"${COPROC[0]}";  # read from co-process
echo $out;
#OUTPUT
"PID : 12551"
"/home/prakash"

Write To Co-Process

now lets try to write to the input of the co-process

#!/bin/bash
coproc (read -r input ; echo ${input});
echo "PID : ${COPROC_PID}";
echo "Hello from Main" >&"${COPROC[1]}" # send it to co-process
read -r out <&"${COPROC[0]}";  # receive it from co-process
echo "Output from co-process is : $out";
#OUTPUT
"PID : 14524"
"Output from co-process is : Hello from Main"

(2) using &

well we can also create tasks asynchronously with a & operator. only difference is we do not have control over input and output of the co-process created. the output of co-process is simply thrown to the calling process

#!/bin/bash
function hel(){
    echo "hello from hel ... sleeping ...";
    sleep 2;
    echo "bye from hel ... "
}
function wel(){
    echo "hello from wel ... sleeping ...";
    sleep 2;
    echo "bye from wel ..."
}
hel & wel
#OUTPUT
hello from hel ... sleeping ...
hello from wel ... sleeping ...
bye from hel ... 
bye from wel ...

Did you find this article valuable?

Support Prakash Choudhary by becoming a sponsor. Any amount is appreciated!