powerpete
powerpete

Reputation: 3052

bash wait still waits for a terminated (piped) process

I've a bash script similar to this one:

#!/bin/sh -x
...
midori -e Fullscreen -a "myurl" 2>&1 | grep -qe "===RESTART===" &
GREP_PID=$!

.. do other stuff with midori etc.

#wait until midori send ===RESTART===
echo Wait for $GREP_PID
wait $GREP_PID
killall -TERM midori
...

Most of them work as expected. But the latest wait will not unblock, after the grep process is dead. I've checked with pstree for the running process. so midori and grep are startet correct. After a while midori send ===RESTART=== and the grep process is terminated (grep is no more visible with pstree). But the wait never finishes.

Whats is the reason for this? How to "enforce" the wait to continue, when the grep process is terminated?

Upvotes: 0

Views: 75

Answers (2)

pynexj
pynexj

Reputation: 20797

See following example:

[STEP 105] # sleep 1000 | sleep 10 &
[1] 45230
[STEP 106] # echo $!
45230
[STEP 107] # ps p 45230
   PID TTY      STAT   TIME COMMAND
 45230 pts/8    S      0:00 sleep 10
[STEP 108] #

As we can see, for command1 ... | command2 ... &, the $! is the PID of command2. So when wait $! completes, only command2 has exited and command1 may still be running. So if you want to wait for both command1 and command2 you shoud use the job ID (%%, %1, %2, ...). Or you can just run wait (without a parameter) to wait for all jobs.

Upvotes: 1

lojza
lojza

Reputation: 1901

Not sure if your $GREP_PID contains right value. Try:

(midori -e Fullscreen -a "myurl" 2>&1 | grep -qe "===RESTART===")&

Upvotes: 1

Related Questions