[kwlug-disc] bash subprocesses & traps
John Steel
john at jskw.ca
Sun Jul 28 12:18:43 EDT 2024
I’m having trouble figuring out how to manage a subprocess… I’m probably overcomplicating this…
I’ve made a script called checksum.sh. I want it to keep moving data from a fifo to sha256sum until it’s terminated. But it seems when I kill it the cat and sha256sum are gone before my finalize method is called? If I can kill cat and let that sub shell exit gracefully I think I should see the sha256sum come out on stderr.
#!/bin/bash
# This is checksum.sh
FIFO_FILE="${FIFO_FILE:-sha256sum_fifo}"
CAT_PID_FILE="$(mktemp -p /dev/shm $$_cat_pid.XXXXXX)"
export CAT_PID_FILE FIFO_FILE
mkfifo "$FIFO_FILE"
finalize() {
pgrep -fl "cat fifo $FIFO_FILE" > /dev/stderr
pgrep -fl sha256sum > /dev/stderr
cat_pid="$(cat "$CAT_PID_FILE")"
rm "$CAT_PID_FILE"
kill -s SIGTERM "$cat_pid" && wait "$cat_pid"
exit 0
}
trap finalize SIGTERM
trap finalize SIGHUP
trap finalize SIGINT
trap finalize SIGQUIT
# Start the cat process and capture its PID
while [ -f "$CAT_PID_FILE" ]; do
cat "$FIFO_FILE" & cat_pid=$!
echo "$cat_pid" > "$CAT_PID_FILE"
wait "$cat_pid"
sleep 0.01
done | sha256sum > /dev/stderr
Here’s how I’m running it:
docker run -it -v $PWD:/app alpine sh -xc '
apk add bash procps
export FIFO_FILE="$(mktemp -u -p /dev/shm fifo_$$.XXXXXX)"
bash -x /app/checksum.sh &
sleep 0.2
jobs
ps -ef --forest
echo "First data to hash" > $FIFO_FILE
sleep 0.2
ps -ef --forest
echo "More data to hash" > $FIFO_FILE
kill %1
sleep 1
‘
Am I missing something obvious? If it’s possible without the loop that’d be great too but I found that if I connect sha256sum directly to the fifo it exits after the first write to the fifo.
Should I learn how to use socat for this? From a few of the things I’ve read it sounds like it could make this simpler?
-------------- next part --------------
A non-text attachment was scrubbed...
Name: smime.p7s
Type: application/pkcs7-signature
Size: 1355 bytes
Desc: not available
URL: <http://mail.kwlug.org/pipermail/kwlug-disc_kwlug.org/attachments/20240728/317dcc4d/attachment.p7s>
More information about the kwlug-disc
mailing list