Skip to main content

llama.cpp — Shutdown & Cleanup

4.1 Signal Handling

The server catches the following signals:

SignalPlatformHandler LocationBehavior
SIGINTUnix/macOSserver.cpp:302-306 sigaction()Graceful shutdown
SIGTERMUnix/macOSserver.cpp:307 sigaction()Graceful shutdown
CTRL_C_EVENTWindowsserver.cpp:309-312 SetConsoleCtrlHandler()Graceful shutdown

Signal Handler Implementation (server.cpp:27-36)

static void signal_handler(int signal) {
if (is_terminating.test_and_set()) {
// Second Ctrl+C: force exit
fprintf(stderr, "Received second interrupt, terminating immediately.\n");
exit(1);
}
shutdown_handler(signal);
}

Key design: an atomic_flag (is_terminating) ensures that:

  • First SIGINT/SIGTERM: Triggers graceful shutdown via shutdown_handler
  • Second SIGINT/SIGTERM: Calls exit(1) immediately — escape hatch if graceful shutdown hangs

4.2 Shutdown Sequence

Single-Model Server (server.cpp:294-344)

  1. Signal receivedsignal_handler() called
  2. Set terminating flagis_terminating.test_and_set() prevents double-handling
  3. Invoke shutdown_handler — calls ctx_server.terminate() (server.cpp:296)
  4. ctx_server.terminate() — calls queue_tasks.terminate() which unblocks start_loop()
  5. Main loop exitsstart_loop() returns (server.cpp:336)
  6. Execute cleanup (server.cpp:257-262):
    • ctx_http.stop() — stops HTTP server, closes listening socket
    • ctx_server.terminate() — waits for in-flight inference tasks
    • llama_backend_free() — releases GGML backend resources
  7. Join HTTP thread (server.cpp:339-340) — ctx_http.thread.join()
  8. Join monitor thread (server.cpp:342-343) — if child server mode
  9. Print timing stats (server.cpp:346-353)
  10. Exit with code 0

Router Server (server.cpp:233-248)

  1. Signal receivedsignal_handler()ctx_http.stop()
  2. HTTP server stops — main thread unblocks from thread.join() (server.cpp:319-321)
  3. Cleanup (server.cpp:236-242):
    • models_routes->models.unload_all() — terminates all child server processes
    • llama_backend_free()
  4. Exit

4.3 Resource Cleanup Inventory

ResourceCleanup MethodLocation
HTTP serverctx_http.stop()server-http.cpp
Inference queuequeue_tasks.terminate()server-queue.cpp
llama_contextllama_free()llama.cpp (via server_context destructor)
llama_modelllama_model_free()llama.cpp (via server_context destructor)
KV cacheImplicit in context freellama-context.cpp:~llama_context
GGML backendsllama_backend_free()ggml-backend.cpp
GPU VRAMggml_backend_buffer_free()per-backend (cuda, metal, etc.)
Memory-mapped modelmunmap() / UnmapViewOfFile()llama-mmap.cpp:~llama_mmap
Child processesmodels.unload_all()server-models.cpp
Thread poolggml_threadpool_free()ggml-threading.cpp
Sampler chainllama_sampler_free()llama-sampler.cpp
Grammarllama_grammar_free()llama-grammar.cpp
LoRA adaptersllama_adapter_lora_free()llama-adapter.cpp