[kwlug-disc] bash subprocesses & traps

Chris Frey cdfrey at foursquare.net
Sun Jul 28 12:56:53 EDT 2024


I'd recommend using some other mechanism of "end of stream" rather
than killing your script, since, as you found out, it halts all processing.

Perhaps instead of kill, rename the file:

	echo "More data to hash" > $FIFO_FILE
	# rename it so while loop exits
	mv "$FIFIO_FILE" "$FIFO_FILE-finished"
	# send empty data to trigger a fifo pipe close on the waiting cat
	cat /dev/null > "$FIFO_FILE-finished"

- Chris


On Sun, Jul 28, 2024 at 12:18:43PM -0400, John Steel via kwlug-disc wrote:
> 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? 



> _______________________________________________
> kwlug-disc mailing list
> To unsubscribe, send an email to kwlug-disc-leave at kwlug.org
> with the subject "unsubscribe", or email
> kwlug-disc-owner at kwlug.org to contact a human being.




More information about the kwlug-disc mailing list