write_or_die: handle EPIPE in async threads

When write_or_die() sees EPIPE, it treats it specially by converting it into a SIGPIPE death. We obviously cannot ignore it, as the write has failed and the caller expects us to die. But likewise, we cannot just call die(), because printing any message at all would be a nuisance during normal operations. However, this is a problem if write_or_die() is called from a thread. Our raised signal ends up killing the whole process, when logically we just need to kill the thread (after all, if we are ignoring SIGPIPE, there is good reason to think that the main thread is expecting to handle it). Inside an async thread, the die() code already does the right thing, because we use our custom die_async() routine, which calls pthread_join(). So ideally we would piggy-back on that, and simply call: die_quietly_with_code(141); or similar. But refactoring the die code to do this is surprisingly non-trivial. The die_routines themselves handle both printing and the decision of the exit code. Every one of them would have to be modified to take new parameters for the code, and to tell us to be quiet. Instead, we can just teach write_or_die() to check for the async case and handle it specially. We do have to build an interface to abstract the async exit, but it's simple and self-contained. If we had many call-sites that wanted to do this die_quietly_with_code(), this approach wouldn't scale as well, but we don't. This is the only place where do this weird exit trick. Signed-off-by: Jeff King <peff@peff.net> Signed-off-by: Junio C Hamano <gitster@pobox.com>

Jeff King committed Feb 24, 2016 at 02:40 UTC 9658846ce3d379b9ff8010a2ed326fcafc10eb82
3 files changed +15
run-command.c
+10
@@ -633,6 +633,11 @@ int in_async(void)
633 return !pthread_equal(main_thread, pthread_self());
634 }
635
636 +void NORETURN async_exit(int code)
637 +{
638 + pthread_exit((void *)(intptr_t)code);
639 +}
640 +
641 #else
642
643 static struct {
@@ -678,6 +683,11 @@ int in_async(void)
683 return process_is_async;
684 }
685
686 +void NORETURN async_exit(int code)
687 +{
688 + exit(code);
689 +}
690 +
691 #endif
692
693 int start_async(struct async *async)
run-command.h
+1
@@ -121,5 +121,6 @@ struct async {
121 int start_async(struct async *async);
122 int finish_async(struct async *async);
123 int in_async(void);
124 +void NORETURN async_exit(int code);
125
126 #endif
write_or_die.c
+4
@@ -1,8 +1,12 @@
1 #include "cache.h"
2 +#include "run-command.h"
3
4 static void check_pipe(int err)
5 {
6 if (err == EPIPE) {
7 + if (in_async())
8 + async_exit(141);
9 +
10 signal(SIGPIPE, SIG_DFL);
11 raise(SIGPIPE);
12 /* Should never happen, but just in case... */