<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
  <channel>
    <title>Asyncio on 魔都水滴</title>
    <link>https://blog.margrop.net/categories/asyncio/</link>
    <description>Recent content in Asyncio on 魔都水滴</description>
    <generator>Hugo -- gohugo.io</generator>
    <language>zh-CN</language>
    <lastBuildDate>Fri, 19 Jun 2026 10:58:00 +0800</lastBuildDate>
    <atom:link href="https://blog.margrop.net/categories/asyncio/index.xml" rel="self" type="application/rss+xml" />
    <item>
      <title>Ubuntu 关机要等 90 秒?Python asyncio 服务不肯接 SIGTERM 的排查与修复</title>
      <link>https://blog.margrop.net/post/ubuntu-shutdown-stuck/</link>
      <pubDate>Fri, 19 Jun 2026 10:58:00 +0800</pubDate>
      <guid>https://blog.margrop.net/post/ubuntu-shutdown-stuck/</guid>
      <description>&lt;blockquote&gt;&#xA;&lt;p&gt;&lt;strong&gt;先说结论&lt;/strong&gt;&lt;/p&gt;&#xA;&lt;p&gt;这台升级到 24.04 的代理机,关机变成了一件折磨人的事:&lt;code&gt;systemctl reboot&lt;/code&gt; 之后,SSH 不掉、灯不灭,要干等 &lt;strong&gt;90 秒&lt;/strong&gt; 才进入真正的 shutdown 流程。journalctl 里很明确:&lt;code&gt;smart-proxy.service: State &#39;stop-sigterm&#39; timed out. Killing.&lt;/code&gt;——systemd 给了 SIGTERM,等 90 秒没人响应,只能 SIGKILL 强杀。&lt;/p&gt;&#xA;&lt;p&gt;根因不是 systemd 的错,也不是 Ubuntu 的错,是 &lt;strong&gt;Python 的 asyncio 服务在收到 SIGTERM 后,没有真正去结束它的子任务&lt;/strong&gt;——它正卡在某个 &lt;code&gt;socket.recv&lt;/code&gt; 上,Python 解释器根本不主动去看&amp;quot;有人叫我走&amp;quot;。&lt;/p&gt;&#xA;&lt;p&gt;修复分两步,缺一不可:&lt;strong&gt;(1)&lt;/strong&gt; 给两个 Python unit 写 systemd drop-in,把 &lt;code&gt;TimeoutStopSec&lt;/code&gt; 从默认的 90s 缩到 20s;&lt;strong&gt;(2)&lt;/strong&gt; 在 Python 服务里主动遍历 &lt;code&gt;asyncio.all_tasks()&lt;/code&gt;,收到 SIGTERM 后把所有 in-flight 的 handler &lt;code&gt;cancel()&lt;/code&gt; 掉,再用 &lt;code&gt;asyncio.wait_for(self.stop(), timeout=10)&lt;/code&gt; 包一层做兜底。改完之后,同样一次 &lt;code&gt;reboot&lt;/code&gt;,从 90 秒掉到 1 秒。&lt;/p&gt;&#xA;&lt;/blockquote&gt;</description>
    </item>
  </channel>
</rss>
