简体   繁体   中英

Shell script: How to restart a process (with pipe) if it dies

I currently use the technique described in How do I write a bash script to restart a process if it dies? by lhunath in order to restart a dead process.

until myserver; do
    echo "Server 'myserver' crashed with exit code $?.  Respawning.." >&2
    sleep 1
done

But rather than just invoking the process myserver , I would like to invoke such a thing:

 myserver 2>&1 | /usr/bin/logger -p local0.info &

How to use the first technique with a process with pipe?

The until loop itself can be piped into logger :

until myserver 2>&1; do
    echo "..."
    sleep 1
done | /usr/bin/logger -p local0.info &

since myserver inherits its standard output and error from the loop (which inherits from the shell).

You can use the PIPESTATUS variable to get the exit code from a specific command in a pipeline:

while :; do
    myserver 2>&1 | /usr/bin/logger -p local0.info
    if [[ ${PIPESTATUS[0]} != 0 ]]
    then echo "Server 'myserver' crashed with exit code ${PIPESTATUS[0]}.  Respawning.." >&2
         sleep 1
    else break
    fi
done

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM