[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: assignment from background process
From: |
Jesse Hathaway |
Subject: |
Re: assignment from background process |
Date: |
Fri, 24 Jan 2020 09:55:47 -0600 |
Another fun option, besides the ones Greg mentioned, is to use a bash coproc as
a background process and then use read with a timeout to poll the coproc for a
response. Below is a silly example of using a coproc to asynchronously send
gigabytes of data to devnull:
#!/bin/bash
copy_to_devnull_daemon() {
read -r count
if dd status=none if=/dev/zero of=/dev/null bs=1G count="${count}"; then
printf 'SUCCESS: Copied %s gigs to /dev/null\n' "${count}"
else
printf 'ERROR: Unable to copy %s gigs to /dev/null\n' "${count}"
fi
}
coproc copy_to_devnull { copy_to_devnull_daemon; }
COPY_TO_DEVNULL_OUT="${copy_to_devnull[0]}"
COPY_TO_DEVNULL_IN="${copy_to_devnull[1]}"
read_copy_to_devnull() {
local timeout_secs
timeout_secs=$1
read -r -t "${timeout_secs}" reply <&"$COPY_TO_DEVNULL_OUT"
printf '%s\n' "$reply"
}
write_copy_to_devnull() {
local count
count=$1
printf '%s\n' "${count}" >&"$COPY_TO_DEVNULL_IN"
}
write_copy_to_devnull '50'
reply=""
while [[ $reply == "" ]]; do
reply=$(read_copy_to_devnull 1)
done
printf 'Reply: "%s"\n' "${reply}"