Alyssa Haroldsen
Alyssa Haroldsen

Reputation: 3731

Ensure destruction of process in bash? (Possibly catch SIGINT)

I'm trying to set up an IO script to allow in/out communication between two FIFO's (one FIFO is for input, the other is for output).

It is necessary for my server to receive output while I am typing input. Both Internals/servout and Internals/servin are FIFOs. I currently implement this by running tail in the background while it is waiting for input.

This is my current code:

#!/bin/bash
# io.sh

tail -f -n 0 Internals/servout &
tpid=$!

read -p ">> " v
while [ $? -eq 0 ] && [ "$v" != "exit" ] && [ "$v" != "quit" ]; do
        echo $v > Internals/servin
        sleep .2
        read -p ">> " v
done

kill $tpid

The major problem I'm running into is when I accidentally type Ctrl-C to end my script. When this happens, the tail -f -n 0 Internals/servout & code continues to run in the background. As you might imagine, that's undesirable.

Is there a way to ensure that the tail command is killed, even when sent SIGINT or similar signals? I'm thinking along the lines of something that can serve the same purpose as the finally keyword in Python, or make the tail command dependent on the current script's process, by using $$.

Feel free to comment on my bad practice - bash is one of my newer languages, and constructive criticism is the quickest way to improve.

Upvotes: 1

Views: 337

Answers (1)

gniourf_gniourf
gniourf_gniourf

Reputation: 46853

You can try something like this:

#!/bin/bash
# io.sh

cleanup() {
    [[ -n $tpid ]] && kill $tpid
}

trap 'cleanup' SIGHUP SIGINT SIGTERM EXIT

tail -f -n 0 Internals/servout &
tpid=$!

quitflag=0
while ((!quitflag)) && read -p ">> " v; do
    case $v in
        exit | quit)
            quitflag=1
            ;;
        help | '?')
            echo "Sorry, I can't help you."
            ;;
    esac
    echo "$v" > Internals/servin
done

Upvotes: 1

Related Questions