Commit df636cd87 for llama.cpp

commit df636cd876f25b5be76f37db0f40e37a42d5ca5b
Author: Xuan-Son Nguyen <son@huggingface.co>
Date:   Fri Dec 4 12:30:31 2026 +0100

    server: making signal handler async-signal-safe (#33481)

diff --git a/tools/server/server-common.cpp b/tools/server/server-common.cpp
index af3ecd6cd..19a6b5e03 100644
--- a/tools/server/server-common.cpp
+++ b/tools/server/server-common.cpp
@@ -14,7 +14,9 @@
 #include <cpp-httplib/httplib.h>

 #include <algorithm>
+#include <cerrno>
 #include <cmath>
+#include <cstdlib>
 #include <filesystem>
 #include <random>
 #include <sstream>
@@ -2308,7 +2310,7 @@ int server_subproc::read_output(server_subproc_stream stream, char * buf, size_t
 #endif
 }

-server_subproc::waiter::waiter() {
+server_fd_waiter::server_fd_waiter() {
 #ifndef _WIN32
     int fds[2];
     GGML_ASSERT(pipe(fds) == 0);
@@ -2320,21 +2322,37 @@ server_subproc::waiter::waiter() {
 #endif
 }

-server_subproc::waiter::~waiter() {
+server_fd_waiter::~server_fd_waiter() {
 #ifndef _WIN32
     close((int) wake_fd[0]);
     close((int) wake_fd[1]);
 #endif
 }

-void server_subproc::waiter::wake() {
+void server_fd_waiter::wake() {
 #ifndef _WIN32
     char c = 1;
     (void) !write((int) wake_fd[1], &c, 1);
 #endif
 }

-void server_subproc::waiter::wait(const std::vector<server_subproc *> & procs, std::vector<bool> & ready, int64_t timeout_ms) {
+void server_signal_notify(server_fd_waiter & waiter, std::atomic<int> & received, int sig) {
+    const int saved_errno = errno; // write() in wake() may change it
+    received.store(sig);
+    waiter.wake();
+    errno = saved_errno;
+}
+
+void server_signal_exit(const char * msg) {
+#ifdef _WIN32
+    fputs(msg, stderr);
+#else
+    (void) !write(STDERR_FILENO, msg, strlen(msg));
+#endif
+    std::_Exit(1);
+}
+
+void server_fd_waiter::wait(const std::vector<server_subproc *> & procs, std::vector<bool> & ready, int64_t timeout_ms) {
     ready.assign(procs.size(), false);
 #ifdef _WIN32
     // no waitable wait exists for anonymous pipes, so poll them in 50 ms steps
diff --git a/tools/server/server-common.h b/tools/server/server-common.h
index 3d5b3f5ef..a9abcac90 100644
--- a/tools/server/server-common.h
+++ b/tools/server/server-common.h
@@ -720,6 +720,33 @@ enum server_subproc_stream {
 // gives the current stdout to the caller as a stream of its own, and sends everything else written to stdout to stderr
 FILE * server_reserve_stdout();

+struct server_subproc;
+
+// wait until one of a set of children has output, wake() is called, or a timeout passes
+struct server_fd_waiter {
+    server_fd_waiter();
+    ~server_fd_waiter();
+
+    // thread-safe and async-signal-safe; on Windows this is a no-op, wait() returns within 50 ms anyway
+    void wake();
+
+    // timeout_ms < 0 waits until data or wake(); ready[i] is set for each child with data on an open pipe (or a broken pipe)
+    void wait(const std::vector<server_subproc *> & procs, std::vector<bool> & ready, int64_t timeout_ms);
+
+private:
+#ifndef _WIN32
+    intptr_t wake_fd[2] = { -1, -1 }; // POSIX self-pipe
+#endif
+};
+
+// async-signal-safe helpers, to be used inside a signal handler
+
+// store sig to received, then wake up the waiter
+void server_signal_notify(server_fd_waiter & waiter, std::atomic<int> & received, int sig);
+
+// print msg to stderr, then exit without running the exit handlers
+[[noreturn]] void server_signal_exit(const char * msg);
+
 // wrapper around common_subproc to manage a child server process
 // mainly used by router mode
 struct server_subproc {
@@ -740,24 +767,11 @@ struct server_subproc {
     // returns the number of bytes read, 0 when nothing is available, -1 when the pipe is closed or broken
     int read_output(server_subproc_stream stream, char * buf, size_t len);

-    // wait until one of a set of children has output, wake() is called, or a timeout passes
-    struct waiter {
-        waiter();
-        ~waiter();
-
-        // thread-safe; on Windows this is a no-op, wait() returns within 50 ms anyway
-        void wake();
-
-        // timeout_ms < 0 waits until data or wake(); ready[i] is set for each child with data on an open pipe (or a broken pipe)
-        void wait(const std::vector<server_subproc *> & procs, std::vector<bool> & ready, int64_t timeout_ms);
-
-    private:
-#ifndef _WIN32
-        intptr_t wake_fd[2] = { -1, -1 }; // POSIX self-pipe
-#endif
-    };
+    using waiter = server_fd_waiter;

 private:
+    friend struct server_fd_waiter;
+
     intptr_t out_handles[SERVER_SUBPROC_STREAMS] = { -1, -1 }; // fd on POSIX, HANDLE on Windows; taken lazily from sproc
     bool     out_closed [SERVER_SUBPROC_STREAMS] = { false, false };
 };
diff --git a/tools/server/server.cpp b/tools/server/server.cpp
index de5bea8b4..1d1774ab5 100644
--- a/tools/server/server.cpp
+++ b/tools/server/server.cpp
@@ -29,15 +29,26 @@
 static std::function<void(int)> shutdown_handler;
 static std::atomic_flag is_terminating = ATOMIC_FLAG_INIT;

-static inline void signal_handler(int signal) {
+#if !defined (_WIN32)
+// shutdown_handler locks mutexes, so it cannot run inside a signal handler
+// the signal handler wakes up server_signal_handlers, which calls shutdown_handler
+// never freed, so a late signal cannot use a destroyed waiter
+static server_fd_waiter * signal_waiter = nullptr;
+static std::atomic<int> signal_received{0};
+#endif
+
+static void signal_handler(int signal) {
     if (is_terminating.test_and_set()) {
         // in case it hangs, we can force terminate the server by hitting Ctrl+C twice
         // this is for better developer experience, we can remove when the server is stable enough
-        fprintf(stderr, "Received second interrupt, terminating immediately.\n");
-        exit(1);
+        server_signal_exit("Received second interrupt, terminating immediately.\n");
     }
-
+#if defined (_WIN32)
+    // the console handler runs on its own thread, so it can call shutdown_handler directly
     shutdown_handler(signal);
+#else
+    server_signal_notify(*signal_waiter, signal_received, signal);
+#endif
 }

 // how the server is run; everything is on when it is the llama-server binary
@@ -342,21 +353,50 @@ static bool server_setup_features(
     return true;
 }

-static void server_install_signal_handlers() {
+// must be declared after the variables used by shutdown_handler, so the thread is joined before they are destroyed
+struct server_signal_handlers {
+    std::thread th;
+    std::atomic<bool> stopping{false};
+
+    void install() {
 #if defined (__unix__) || (defined (__APPLE__) && defined (__MACH__))
-    struct sigaction sigint_action;
-    sigint_action.sa_handler = signal_handler;
-    sigemptyset (&sigint_action.sa_mask);
-    sigint_action.sa_flags = 0;
-    sigaction(SIGINT, &sigint_action, NULL);
-    sigaction(SIGTERM, &sigint_action, NULL);
+        if (signal_waiter == nullptr) {
+            signal_waiter = new server_fd_waiter();
+        }
+        th = std::thread([this]() {
+            std::vector<bool> ready;
+            while (!stopping.load()) {
+                signal_waiter->wait({}, ready, -1);
+                const int signal = signal_received.exchange(0);
+                if (signal != 0) {
+                    shutdown_handler(signal);
+                }
+            }
+        });
+        struct sigaction sigint_action;
+        sigint_action.sa_handler = signal_handler;
+        sigemptyset (&sigint_action.sa_mask);
+        sigint_action.sa_flags = 0;
+        sigaction(SIGINT, &sigint_action, NULL);
+        sigaction(SIGTERM, &sigint_action, NULL);
 #elif defined (_WIN32)
-    auto console_ctrl_handler = +[](DWORD ctrl_type) -> BOOL {
-        return (ctrl_type == CTRL_C_EVENT || ctrl_type == CTRL_BREAK_EVENT) ? (signal_handler(SIGINT), true) : false;
-    };
-    SetConsoleCtrlHandler(reinterpret_cast<PHANDLER_ROUTINE>(console_ctrl_handler), true);
+        auto console_ctrl_handler = +[](DWORD ctrl_type) -> BOOL {
+            return (ctrl_type == CTRL_C_EVENT || ctrl_type == CTRL_BREAK_EVENT) ? (signal_handler(SIGINT), true) : false;
+        };
+        SetConsoleCtrlHandler(reinterpret_cast<PHANDLER_ROUTINE>(console_ctrl_handler), true);
 #endif
-}
+    }
+
+    ~server_signal_handlers() {
+#if defined (__unix__) || (defined (__APPLE__) && defined (__MACH__))
+        if (th.joinable()) {
+            stopping.store(true);
+            signal_waiter->wake();
+            th.join();
+        }
+#endif
+    }
+};

 // once the HTTP server listens: log the addresses and spawn llama-connect if asked, so the port is
 // bound and the child startup health check reaches us. the destructor of connect_proc stops it
@@ -611,8 +651,9 @@ static int server_run_router(common_params & params, int argc, char ** argv, con
         return 1;
     }

+    server_signal_handlers sig_handlers;
     if (opts.install_signal_handlers) {
-        server_install_signal_handlers();
+        sig_handlers.install();
     }

     server_connect connect_proc;
@@ -784,8 +825,9 @@ static int server_run_instance(common_params & params, server_role & role, commo
         ctx_server.terminate();
     };

+    server_signal_handlers sig_handlers;
     if (opts.install_signal_handlers) {
-        server_install_signal_handlers();
+        sig_handlers.install();
     }

     server_connect connect_proc;
diff --git a/tools/server/tests/unit/test_basic.py b/tools/server/tests/unit/test_basic.py
index 4cb21905f..c1157b2a0 100644
--- a/tools/server/tests/unit/test_basic.py
+++ b/tools/server/tests/unit/test_basic.py
@@ -3,6 +3,7 @@ import requests
 import signal
 import socket
 import sys
+import time
 from utils import *

 server = ServerPreset.tinyllama2()
@@ -190,3 +191,24 @@ def test_server_sigterm_during_request():
     # the client keeps the connection open, so the HTTP thread must not wait for a result forever
     assert server.process.wait(timeout=10) == 0
     stream.close()
+
+
+@pytest.mark.skipif(sys.platform == "win32", reason="POSIX signal")
+def test_server_second_sigterm():
+    global server
+    server.start()
+    # a client that sends only part of a request holds the shutdown until the read timeout
+    sock = socket.create_connection((server.server_host, server.server_port))
+    sock.sendall(b"POST /completion HTTP/1.1\r\nHost: localhost\r\nContent-Length: 100\r\n\r\n{")
+    # connections are accepted in order, so the one above is accepted once this one is served
+    assert server.make_request("GET", "/health").status_code == 200
+    server.process.send_signal(signal.SIGTERM)
+    # signals of the same type are merged if one is still pending, so wait for the listener to stop first
+    with pytest.raises(requests.exceptions.RequestException):
+        for _ in range(300):
+            requests.get(server.make_url("/health"), timeout=1)
+            time.sleep(0.1)
+    server.process.send_signal(signal.SIGTERM)
+    # exit code 1 means the second signal forced the exit
+    assert server.process.wait(timeout=10) == 1
+    sock.close()