2

I'm looking for a lightweight solution to kill a command with output redirection if it hangs. my current solution

if [[ -w /tmp/mypipe ]]; then
  timeout --kill-after 10 5 echo "1" > /tmp/mypipe
fi

works only if the left part of the command does not work correctly (e.g. no one does read from the pipe). But I discovered situation, where the redirection hangs -- which at least are an issue of not completely synchronized tasks, which I can't solve now.

There are several related questions like this, this or that. The last one mostly covers my question, but I'm still looking for a more slim solution. It suggests to work like

( CMDPID=$BASHPID; \
  (sleep 5; kill -9 $CMDPID >& /dev/null) & echo "1" > /tmp/mypipe )

But this spawns two new bash processes. Is there a more lightweight solution for that problem?

Community
  • 1
  • 1
Daniel
  • 303
  • 3
  • 8

1 Answers1

1

Keep in mind that each spawned bash process will share the vast majority of its memory with the parent process, so it's not tripling memory usage like top would have you believe.

If you still want to try to optimize, timeout 5 tee /tmp/mypipe <<< "1" > /dev/null will spawn a timeout and a tee process instead.

that other guy
  • 116,971
  • 11
  • 170
  • 194
  • Well, thanks for the input. I really did not think about the implicit efficiency of the process management. If I find the time, I will try your solution as well. – Daniel Jun 01 '13 at 08:44