I'm writing data to a pipe in a parent process. The parent process creates a background job that reads data from the pipe & write it to the screen & to a log file.
How can I know when to kill the background job? wait command simply waits forever. I prefer to not use a token to detect the "end of output". Code example:
function log()
{
if [ -z "$counter" ]; then
counter=1
else
(( ++counter ))
fi
if ! [[ -z "$teepid" ]]; then
# ***** How can I know if it's safe to kill here?
kill $teepid
fi
# Display text-to-be-logged on screen
# & write text-to-be-logged to it's corresponding log file
tee <"$pipe" 1>&4 "${logs_dir}/${counter}_${1// /_}" &
teepid=$!
}
logs_dir="/path/to/log/dir"
pipe_dir=$(mktemp -d)
pipe="${pipe_dir}/cmds_output"
mkfifo "$pipe"
exec 3<>"$pipe" # link file descriptor (FD) #3 to $pipe for r/w
exec 4<&1 # save value of FD1 to FD4
exec 1>&3 # redirect all output to FD3
log # Logs the following code block
{
# ... Many bash commands ...
}
log # Logs the following code block
{
# ... Many bash commands ...
}
if ! [[ -z "$teepid" ]]; then
# ***** How can I know if it's safe to kill here? Maybe it's still logging
kill $teepid;
fi
Edit:
I tried:
exec 3>&-
#exec 1>&- # Have tried also uncommenting this row
wait $teepid
exec 3<>"$pipe"
exec 1>&3
kill $teepid
but the wait command still hangs...
I found that ps -o pid,ppid,s --pid $teepid shows the state of the process. Should I count on that?