bug-bash
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: How to safely pipe output to tee?


From: Micah Cowan
Subject: Re: How to safely pipe output to tee?
Date: Mon, 07 Mar 2011 12:58:12 -0800
User-agent: Mozilla/5.0 (X11; U; Linux x86_64; en-US; rv:1.9.2.14) Gecko/20110223 Thunderbird/3.1.8

(03/07/2011 12:22 PM), Steven W. Orr wrote:
> Sorry, but I'm not sure I see why this helps.
> 
> I think it says (I assume you meant a space between the 100 and the
> greater than, otherwise you're just trying to close channel 100):
>
> foo='sleep 100 >&- 2>&- &'

Yeah. That's how I typed it. Your mailer seems to have screwed it up,
because mine shows the original like that.

> "Sleep for 100 seconds and then close channel 1 and channel 2."

No. Sleep for 100 seconds, immediately closing channel 1 and channel 2
for that program ("sleep 100" just represents an arbitrary program to
background).

> Maybe. But how do I harvest the status of the command, since the sleep
> will always succeed?

The example was meant to show what to do with the background processes
you said you spawn. You obviously can't harvest the statuses of
processes that haven't actually exited yet. I assumed you meant the
status of the overall "foo" command.

The central idea is that you make sure that any background processes
don't keep the pipe open. So the general pattern is:

  foo='arbitrary-foo-commands; bkgnd-procA >&- 2>&- & \
bkgnd-procB >&- 2>&- & more-arbitrary-foo-commands'

(If your mail-reader screws that up too, then you'll have to adjust...
maybe see if looking at the mail's source improves matters)

Then, evaluating foo will return the final exit status (from the final
command), while the background processes will be prevented from writing
to the pipe (which will be closed when foo exits).

(Note, by the way, that the 2>&- bits are only necessary because you did
2>&1 on your eval.)

I don't know whether your "real" foo gives you that level of control
over what you do with your background tasks; so long as you can control
their output descriptors, you can do something along these lines (which
is really the proper way to deal with this issue). If you do not have
that level of control over them, then there won't be any better way
(that I can think of) than your current solution.

If, for instance, your foo is something like "mydaemon -d", where it
does some cursory error-checking, and then if everything seems fine,
spawns to the background, then your ability to do what you want is
limited. The only real salvation is if "mydaemon" has a "-q" option that
not only prevents output except in cases of error, but actually causes
it to close its stdout and stderr so that the pipe no longer has a writer.

-- 
Micah J. Cowan
http://micah.cowan.name/



reply via email to

[Prev in Thread] Current Thread [Next in Thread]