Re: [PATCH] Properly handle short writes in sigint handlers

Subject: Re: [PATCH] Properly handle short writes in sigint handlers

Date: Sat, 24 Dec 2011 19:38:50 -0500

To: Tomi Ollila

Cc: notmuch@notmuchmail.org

From: Austin Clements


Quoth Tomi Ollila on Dec 23 at  2:30 pm:
> On Fri, 23 Dec 2011 08:10:33 +0000, David Edmondson <dme@dme.org> wrote:
> > Sorry for being slow.
> > 
> > Can you describe the situation in which you expect a write to stderr to
> > be a short write? (Without error.)
> 
> In the following hypothetical case (correct me if I'm wrong :):
> 
> * There is 4096 byte buffer in tty driver.
> * Stderr is in blocking-mode (the usual case).
> * There is already 4090 bytes in that buffer that has not been read.
> * One attemtps to write "Stopping...         \n" there (blocks).
> * Somehow the system call is interrupted (and SA_RESTART not set)
>   -- write() should return 6 bytes written.

This is one possibility.  It's also possible it will write no bytes
and fail with EINTR.  Depending on the type of the stderr file
descriptor, it's possible for write to return immediately with 6,
even without a signal interrupting it.

> But, if the buffer is full already, does the write() system call return
> with -1 and EINTR set ?

write only returns EINTR if it was interrupted by a signal before
anything was written.  If the buffer is full already, write will block
(unless it's in non-blocking mode, in which case it will write nothing
and fail with EAGAIN or EWOULDBLOCK).

> If there is enough space for all data in that buffer to begin with, 
> write() should be atomic.
> 
> > In that situation, what guarantee is there that the loop you've written
> > will terminate?
> 
> If write() keeps returning 0 then it will not terminate (I guess this never
> happens). Also, it never terminates if write blocks indefinitely 
> (with or without that loop).

I believe the only way write can return 0 is if you pass it a zero
length.

> > We're not talking about safeguarding a users' data here - this is a
> > short message to indicate that a tool is terminating due to a signal.
> > I'm concerned that the solution is worse than the problem.
> 
> I'm also in favor of "opportunistic" write *in this particular case*
> 
> In case that write fails there is most probably more serious things going
> on (all resources eaten, hardware problem, etc) and trying to push these
> writes forward doesn't help.

This I find more persuasive.  I've been concerned about notmuch doing
strange things (with admittedly minor consequences) under common
circumstances (like transient buffer overflows), but you're right that
more severe circumstances could warrant an opportunistic approach.  Of
course, we're also not depending on the sigint handler for
correctness; if notmuch somehow wedges in it then you're notmuch worse
off than you would be otherwise.

Thread: