SDL: Make sure we ignore SIGPIPE so we don't crash if we write when the pipe is closed

From ec5d280c9001918820225952ea44076529978d2a Mon Sep 17 00:00:00 2001
From: Sam Lantinga <[EMAIL REDACTED]>
Date: Sat, 14 Sep 2024 22:08:46 -0700
Subject: [PATCH] Make sure we ignore SIGPIPE so we don't crash if we write
 when the pipe is closed

---
 src/process/posix/SDL_posixprocess.c | 25 +++++++++++++++++++++++++
 1 file changed, 25 insertions(+)

diff --git a/src/process/posix/SDL_posixprocess.c b/src/process/posix/SDL_posixprocess.c
index 23a286023598d..ea67d82a68926 100644
--- a/src/process/posix/SDL_posixprocess.c
+++ b/src/process/posix/SDL_posixprocess.c
@@ -72,6 +72,28 @@ static bool SetupStream(SDL_Process *process, int fd, const char *mode, const ch
     return true;
 }
 
+static void IgnoreSignal(int sig)
+{
+#ifdef HAVE_SIGACTION
+    struct sigaction action;
+
+    sigaction(SIGPIPE, NULL, &action);
+#ifdef HAVE_SA_SIGACTION
+    if (action.sa_handler == SIG_DFL && (void (*)(int))action.sa_sigaction == SIG_DFL) {
+#else
+    if (action.sa_handler == SIG_DFL) {
+#endif
+        action.sa_handler = SIG_IGN;
+        sigaction(sig, &action, NULL);
+    }
+#elif defined(HAVE_SIGNAL_H)
+    void (*ohandler)(int) = signal(sig, SIG_IGN);
+    if (ohandler != SIG_DFL && ohandler != SIG_IGN) {
+        signal(sig, ohandler);
+    }
+#endif
+}
+
 static bool CreatePipe(int fds[2])
 {
     if (pipe(fds) < 0) {
@@ -82,6 +104,9 @@ static bool CreatePipe(int fds[2])
     fcntl(fds[READ_END], F_SETFD, fcntl(fds[READ_END], F_GETFD) | FD_CLOEXEC);
     fcntl(fds[WRITE_END], F_SETFD, fcntl(fds[WRITE_END], F_GETFD) | FD_CLOEXEC);
 
+    // Make sure we don't crash if we write when the pipe is closed
+    IgnoreSignal(SIGPIPE);
+
     return true;
 }