Files
cpp-httplib/docs-src/pages/ja/cookbook/s19-graceful-shutdown.md
T
yhirose 36065c657c Bound the wait of WebSocket::close() as a whole
close() waited for the peer's Close reply with a read timeout that
applied to each read, so a peer that kept sending other frames, or sent
one frame a byte at a time, held close() for as long as it liked.

Bound the wait as a whole. close() sets the stream's max timeout, which
shortens each wait to what is left, and stops reading frames at the
deadline, which matters when the peer keeps the socket full and no wait
happens at all. WebSocketSSLStream gains set_max_timeout(), the one
stream a WebSocket uses that lacked it.

A read() running on another thread when close() is called still waits
for the reply up to its own read timeout, as documented. The docs now
say how to bound it.
2026-11-17 00:56:06 -05:00

3.2 KiB
Raw Blame History

title, order, status
title order status
S19. グレースフルシャットダウンする 38 draft

サーバーを止めるにはServer::stop()を呼びます。処理中のリクエストがある状態でも安全に呼べるので、SIGINTやSIGTERMを受け取ったときにこれを呼べば、グレースフルなシャットダウンが実現できます。

基本の使い方

httplib::Server svr;

svr.Get("/", [](const auto &, auto &res) { res.set_content("ok", "text/plain"); });

std::thread t([&] { svr.listen("0.0.0.0", 8080); });

// メインスレッドで入力を待つなど
std::cin.get();

svr.stop();
t.join();

listen()はブロックするので、別スレッドで動かして、メインスレッドからstop()を呼ぶのが典型的なパターンです。stop()後はlisten()が戻ってくるので、join()できます。

シグナルでシャットダウンする

SIGINT(Ctrl+C)やSIGTERMを受け取ったときに停止させる例です。

#include <csignal>

httplib::Server svr;

// グローバル領域に置いてシグナルハンドラからアクセス
httplib::Server *g_svr = nullptr;

int main() {
  svr.Get("/", [](const auto &, auto &res) { res.set_content("ok", "text/plain"); });

  g_svr = &svr;
  std::signal(SIGINT,  [](int) { if (g_svr) g_svr->stop(); });
  std::signal(SIGTERM, [](int) { if (g_svr) g_svr->stop(); });

  svr.listen("0.0.0.0", 8080);
  std::cout << "server stopped" << std::endl;
}

stop()はスレッドセーフで、シグナルハンドラの中から呼んでも安全です。listen()がメインスレッドで動いていても、シグナルを受けたら抜けてきます。

処理中のリクエストの扱い

stop()を呼ぶと、新しい接続は受け付けなくなりますが、すでに動いているハンドラは最後まで実行されます。ただし、ストリーミングのようにコンテンツプロバイダで送っている途中のレスポンスは、その場で打ち切られます。その後、スレッドプールのワーカーが順次終了し、listen()から戻ってきます。これがグレースフルシャットダウンと呼ばれる理由です。

Warning: stop()を呼んでからlisten()が戻るまでには、処理中のリクエストが終わるのを待つ時間がかかります。タイムアウトを強制したい場合は、シャットダウン用のタイマーを別途用意するなど、アプリケーション側の工夫が必要です。

Note: stop()はWebSocketハンドラを中断しません。read()をループで回しているハンドラは相手がつながっている限り動き続け、それが終わるまでlisten()も戻りません。開いているWebSocket接続を記録しておき、シャットダウン時にclose()(CloseStatus::GoingAwayなど)で閉じてください。そのあとハンドラのread()は、相手のClose応答を読み込みタイムアウト(既定は300秒)まで待ちます。短くしたい場合は、ループの前にset_read_timeout()を呼んでください。その場合、相手が黙っている間はread()がTimeoutを返すので、ループ側で扱う必要があります。