Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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 ))

    if ! [[ -z "$teepid" ]]; then
        # ***** How can I know if it's safe to kill here?
        kill $teepid
    # 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// /_}" &


pipe_dir=$(mktemp -d)
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;


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?

share|improve this question
up vote 0 down vote accepted

Just close the pipe when you are done. The child process will reach EOF and should exit.

share|improve this answer
What do you mean by "close the pipe"? What's the code for that..? – Dor Jul 13 '11 at 18:18
You created it by redirecting fd number 3 to the pipe, so you can close it by redirecting it somewhere else ( /dev/null maybe? ). – psusi Jul 13 '11 at 18:24
Actually it looks like you can close an fd by redirecting it to "&-", as in 3>&-. – psusi Jul 13 '11 at 18:28
I tried that... doesn't help – Dor Jul 13 '11 at 18:30
@Dor need to be more specific. You also don't want either of those kill $teepid statements. – psusi Jul 13 '11 at 18:34

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.