Home > Blockchain >  Run two programs in while keeping stdin of the first connected
Run two programs in while keeping stdin of the first connected

Time:12-03

I have two programs, prog1 and prog2, prog2 takes the PID of prog1 as argument and they have to run in parallel.

I need stdin and stdout of prog1 to stay connected to the shell, note that it's not an interactive shell.

I tried like this, but stdin of prog1 is not connected to the shell:

#!/bin/bash
./prog1 & (./prog2 $! 1>&2 0<&-)
fg

CodePudding user response:

From bash manual:

If a command is terminated by the control operator ‘&’, the shell executes the command asynchronously in a subshell. This is known as executing the command in the background, and these are referred to as asynchronous commands. The shell does not wait for the command to finish, and the return status is 0 (true). When job control is not active (see Job Control), the standard input for asynchronous commands, in the absence of any explicit redirections, is redirected from /dev/null.

So let's make some explicit redirections! The following scripts:

==> prog1 <==
#!/bin/bash
set -x
read data
echo "$data"


==> prog2 <==
#!/bin/bash
while kill -0 "$1"; do sleep 0.1; done

==> script.sh <==
#!/bin/bash
set -x
./prog1 <&0 &
#       ^^^^   - the important part
./prog2 $! >&2 <&-
wait

When executing ./script.sh results in:

$ LC_ALL=C ./script.sh
  ./prog2 1835980
  ./prog1
  read data
bla
  echo bla
bla
./prog2: line 2: kill: (1835980) - No such process
  wait
  •  Tags:  
  • bash
  • Related