DIT Robotics · Software courses · OS‑1: Files and ProcessesDIT Robotics · 軟體課程 · OS‑1:檔案與 process

Ctrl+C Is Not Enough: the Life and Death of a ProcessCtrl+C 不夠用:process 的生與死

Every node you start is a Linux process, and the Linux kernel decides how it starts, how it stops and what it may touch. In this session we start a small robot stack, try to stop it, and fail. Then we find out why. On the way you learn the operating-system ideas behind most "it won't stop", "it died when SSH dropped", "permission denied" and "works on my machine" problems: processes, signals, daemons, file permissions and shared libraries.

你啟動的每個 node 都是一個 Linux process,而 Linux 核心決定它怎麼啟動、怎麼停止、可以碰什麼。這堂課我們啟動一個小小的機器人系統,試著把它停掉,結果失敗了;然後找出原因。過程中你會學到大部分「停不下來」、「SSH 一斷就死掉」、「permission denied」、「在我電腦上可以跑」問題背後的作業系統觀念:process、signal、daemon、檔案權限和共享函式庫。

How to use this page. The numbered Parts are what we do together in the session. Boxes and Parts marked Go deeper hold ideas that take longer to sink in: come back to them after the session. Every command here runs in the course container: see Before the session below. The 中文 button (or the L key) switches the page to Chinese.

怎麼用這一頁。有編號的部分是課堂上一起做的。標成延伸的方塊和部分,放的是比較需要時間消化的觀念,課後再回來看。這裡每個指令都在課程容器裡跑:見下面的上課前。English 按鈕(或 L 鍵)可以切回英文。

Before the session上課前
Open the course container開啟課程容器

If you haven't yet, do the one-time setup on the course home page: clone the repository and build dit-course. Then git pull, and from the top of the repository start terminal T1:

如果還沒做過,先照課程首頁做一次設定:clone repository,建置 dit-course。然後 git pull,在 repository 的最上層開終端機 T1:

docker run -it --rm --name os1 -v "$PWD/os-1/code":/code dit-course bash
# more terminals (T2, T3, ...), each in a new window:
docker exec -it os1 bash

-v puts this course's code/ folder inside the container at /code, so a file you edit on your laptop changes inside the container too.

-v 會把這堂課的 code/ 資料夾放進容器的 /code,所以你在筆電上改檔案,容器裡也跟著改。

Part 1第 1 部分You stopped it. It's still running.你停掉它了,它還在跑

Our running example is a tiny robot stack: three programs started by one launch file. fake_mcu plays a microcontroller: it sends wheel ticks over a fake serial port, /tmp/mcu. driver reads that port and publishes /wheel_ticks. monitor prints the latest value once a second.

我們的範例是一個很小的機器人系統:一個 launch 檔啟動三個程式。fake_mcu 扮演微控制器:透過一個假的序列埠 /tmp/mcu 送出輪子的 tick。driver 讀這個序列埠,發布 /wheel_ticks。monitor 每秒印一次最新的值。

def py(script):
    return ExecuteProcess(cmd=['python3', os.path.join(HERE, script)], output='screen')

def generate_launch_description():
    return LaunchDescription([
        py('fake_mcu.py'),
        TimerAction(period=1.0, actions=[py('driver.py'), py('monitor.py')]),
    ])

The whole stack is in code/: robot.launch.py, fake_mcu.py, driver.py, monitor.py.

整個系統在 code/:robot.launch.py、fake_mcu.py、driver.py、monitor.py。

In terminal T1 we start it:

在終端機 T1 啟動它:

# T1
$ ros2 launch robot.launch.py
[INFO] [python3-1]: process started with pid [472]
[python3-1] fake_mcu: /tmp/mcu -> /dev/pts/1
[INFO] [python3-2]: process started with pid [474]
[INFO] [python3-3]: process started with pid [476]
[python3-2] [INFO] [driver]: reading /tmp/mcu
[python3-3] [INFO] [monitor]: ticks = 63
[python3-3] [INFO] [monitor]: ticks = 133

Normally you stop a launch by pressing Ctrl+C in its terminal, and that works (Part 4 shows why). But sometimes that terminal is out of reach: a start-up script launched it, it runs in a teammate's tmux window, or your SSH session dropped while it ran inside the container (Part 5 shows it keeps running). Then you stop it from another terminal, T2, the way you stop any program: find it with ps, and kill it.

平常你會在 launch 的終端機按 Ctrl+C 停掉它,而且有用(第 4 部分會說明為什麼)。但有時候那個終端機你碰不到:它是開機腳本啟動的、它跑在隊友的 tmux 視窗裡,或它在容器裡跑的時候你的 SSH 斷線了(第 5 部分會看到它還在跑)。這時你只能從另一個終端機 T2 停掉它,就像停掉任何程式一樣:用 ps 找到它,再 kill 掉。

# T2
$ ps -e -o pid,ppid,cmd
    471     463 /usr/bin/python3 /opt/ros/humble/bin/ros2 launch robot.launch.py
    472     471 python3 /code/fake_mcu.py
    474     471 python3 /code/driver.py
    476     471 python3 /code/monitor.py
$ kill 471
# T1
Terminated
$

T1 says Terminated and gives us the prompt back. Done? Back in T2:

T1 印出 Terminated,回到提示字元。停掉了嗎?回到 T2:

# T2
$ ros2 node list
/driver
/monitor
$ ps -e -o pid,ppid,cmd
    472       1 python3 /code/fake_mcu.py
    474       1 python3 /code/driver.py
    476       1 python3 /code/monitor.py

The launch is gone, but all three programs are still running. The nodes still publish, still hold the serial port, and will clash with the next launch you start. Something else changed too: the second column, the parent, was 471 and is now 1.

launch 不見了,但三個程式都還在跑。node 還在發布、還佔著序列埠,下一次啟動 launch 時會跟它們撞在一起。還有一件事變了:第二欄(父 process)原本是 471,現在變成 1。

Why did kill stop the launch but not the nodes it started? And who is "1"? Write your guess down. Part 4 answers it.

為什麼 kill 停掉了 launch,卻沒停掉它啟動的 node?「1」又是誰?把你的猜測寫下來,第 4 部分會回答。

Part 2第 2 部分Inside the computer電腦裡面

Before we look at processes, here is the hardware they run on. You only need four things that hold data and one thing that does the work. Every later Part (and every later course) leans on this picture.

在看 process 之前,先看它們跑在什麼硬體上。你只需要知道四個存放資料的地方,和一個做事的東西。後面每個部分(以及後面每堂課)都會用到這張圖。

The CPU runs instructionsCPU 執行指令

To the CPU, a program is a long list of very simple instructions: load a number, add two numbers, compare, jump to another place in the list. A core is one part of the CPU that runs instructions one after another, driven by a clock: 2.9 GHz means 2.9 billion ticks a second, and a simple instruction takes about one tick. A core works on registers: a few dozen slots inside the core, each holding one number. One register, the program counter, holds which instruction is next.

對 CPU 來說,程式是一長串非常簡單的指令:載入一個數字、把兩個數字相加、比較、跳到清單的另一個位置。核心(core)是 CPU 裡一個接一個執行指令的部分,由時脈驅動:2.9 GHz 代表每秒 29 億次 tick,一個簡單的指令大約花一次 tick。核心在暫存器(register)上工作:核心裡面幾十個小格子,每格放一個數字。其中一個暫存器(program counter)記著下一個要跑的指令在哪裡。

A CPU has several cores, so several programs really run at the same moment. The laptop we ran this course's examples on:

一顆 CPU 有好幾個核心,所以好幾個程式真的可以在同一刻一起跑。我們跑這堂課範例的筆電:

$ lscpu     # selected lines
CPU(s):                                  16
Thread(s) per core:                      2
Core(s) per socket:                      8
CPU max MHz:                             2901.0000
L1d cache:                               256 KiB (8 instances)
L2 cache:                                4 MiB (8 instances)
L3 cache:                                8 MiB (2 instances)

8 cores, each able to run 2 streams of instructions, so Linux sees 16 CPUs. The cache lines come next.

8 個核心,每個能同時跑 2 串指令,所以 Linux 看到 16 個 CPU。cache 那幾行接下來會說明。

Where data lives: fast and small, or big and slow資料放在哪:快而小,或大而慢

A core can only compute on what is in its registers, so data must be brought in from somewhere. There are four levels, and each step down is bigger, cheaper and slower:

核心只能運算暫存器裡的東西,所以資料得從某個地方搬進來。一共有四層,每往下一層就更大、更便宜、也更慢:

one core一個核心 ALU L1L2 L3 memory sticks記憶體條 ctrl flash an M.2 card on the board主機板上的 M.2 卡 Registers暫存器 inside each core在每個核心裡面 ≈0.3 ns · 100s of bytes≈0.3 ns · 幾百位元組 Cache快取 on the CPU chip在 CPU 晶片上 1.7–12 ns · KiB–MiB RAMRAM next to the CPU在 CPU 旁邊 ≈100 ns · 22 GiB SSDSSD further away, on the board更遠,在主機板上 65 µs · 916 GB closer to the core: faster and smaller離核心越近:越快、越小 further away: bigger and slower · only the SSD keeps data at power off越遠:越大、越慢 · 只有 SSD 斷電後還留著資料
Where each one physically is. Drawn simply: a real chip has its parts in other shapes, but in this order. The numbers are the ones measured below.它們實際上在哪裡。這是簡化的圖:真的晶片裡各部分形狀不同,但位置順序就是這樣。數字是下面量到的。

How much slower? We measured it on the same laptop. memory_latency.cpp follows a chain of pointers through arrays of growing size, so every read waits for the one before. A small array stays in the cache; a big one only fits in RAM. A second small program read 4 KiB at random places in a 1 GiB file on the SSD, bypassing the cache:

慢多少?我們在同一台筆電上量過。memory_latency.cpp 在越來越大的陣列裡沿著一串指標走,所以每次讀取都要等前一次。小陣列會留在快取裡;大陣列只放得進 RAM。另一個小程式在 SSD 上一個 1 GiB 的檔案裡隨機讀 4 KiB,不經過快取:

$ ./memory_latency
      16 KiB     1.7 ns per read      fits in L1
     128 KiB     4.1 ns per read      fits in L2
    1024 KiB    11.6 ns per read      fits in L3
    4096 KiB    29.3 ns per read      L3 is full: partly RAM
   65536 KiB    94.0 ns per read      RAM
  524288 KiB   119.7 ns per read      RAM
$ python3 ssd_latency.py
65 us per 4 KiB read                  SSD
time for one read (log scale: each grid line is 10× more) 讀一次要多久(對數刻度:每一條格線多 10 倍) if L1 took 1 s 如果 L1 要 1 秒 0.1 ns1 ns10 ns100 ns1 µs10 µs100 µs Registers暫存器 L1 cache L2 cache L3 cache RAM SSD hundreds of bytes幾百個位元組 32 KiB / core 512 KiB / core 8 MiB 22 GiB 916 GB ≈0.3 ns (1 tick)≈0.3 ns(1 tick) 1.7 ns 4.1 ns 11.6 ns ≈100 ns 65 µs 0.2 s0.2 秒 1 s1 秒 2.4 s2.4 秒 7 s7 秒 about a minute大約 1 分鐘 about 11 hours大約 11 小時
Measured on our laptop, except the register line, which is one clock tick at 2.9 GHz. Sizes are from lscpu, free -h and df -h. Other computers differ in the numbers, never in the order.在我們的筆電上量的,只有暫存器那一行是用 2.9 GHz 的一次 tick 算出來的。容量來自 lscpu、free -h 和 df -h。別的電腦數字會不一樣,但順序永遠一樣。

A read from the SSD takes as long as about 40,000 reads from the cache. That is why a program is copied from the SSD into RAM before it runs, and why the cache exists at all: most of the time, the next thing a program needs is close to the last thing it used, and the cache already has it.

從 SSD 讀一次的時間,大約可以從快取讀 40,000 次。這就是為什麼程式要先從 SSD 複製到 RAM 才能執行,也是快取存在的理由:大部分時候,程式下一個需要的東西就在它剛用過的東西附近,而快取裡已經有了。

The kernel shares all of this核心負責分配這一切

Hundreds of programs want the same cores, the same RAM and the same devices. The Linux kernel is the program that hands them out: which program runs on which core and for how long, which part of RAM belongs to whom, who may use which device. Every other program has to ask the kernel. The rest of this course is about the kernel's rules: for running programs (processes), for stopping them (signals), and for files and devices (permissions).

幾百個程式都想用同樣的核心、同樣的 RAM、同樣的裝置。Linux 核心就是負責分配的那個程式:哪個程式在哪個核心上跑、跑多久,RAM 的哪一塊屬於誰,誰可以用哪個裝置。其他每個程式都得去問核心。這堂課接下來講的,就是核心的規則:關於正在跑的程式(process)、關於停止它們(signal),以及關於檔案和裝置(權限)。

On a robot在機器人上
Two computers, the same ideas兩台電腦,同樣的觀念

A robot usually carries two kinds of computer. The robot computer runs Linux and ROS: a multi-core CPU, gigabytes of RAM, an SSD, and often a GPU (on Jetson-class boards the GPU shares the same RAM). The microcontroller (MCU) drives the motors and reads the encoders: one core at a few hundred MHz, around a megabyte of RAM, no SSD (its program sits in flash memory, which keeps it at power off), and no Linux. The levels and the trade-offs are the same; only the numbers shrink. The fake serial port in this course stands for the wire between them.

機器人通常帶著兩種電腦。機器人電腦跑 Linux 和 ROS:多核心 CPU、好幾 GB 的 RAM、SSD,常常還有 GPU(在 Jetson 這類板子上,GPU 跟 CPU 共用同一塊 RAM)。微控制器(MCU)驅動馬達、讀 encoder:一個幾百 MHz 的核心、大約 1 MB 的 RAM、沒有 SSD(程式放在 flash 記憶體裡,斷電也還在),也沒有 Linux。層級和取捨都一樣,只是數字變小。這堂課裡的假序列埠,代表的就是它們之間的那條線。

Try it動手試
Measure your own computer量你自己的電腦

Start T1 as in Before the session, or use any Linux laptop with g++. Before you run it, guess your RAM number.

照上課前的步驟開 T1,或用任何有 g++ 的 Linux 筆電。執行之前,先猜你的 RAM 數字。

docker run -it --rm --name os1 -v "$PWD/os-1/code":/code dit-course bash
cd /code
g++ -O2 -o /tmp/memory_latency memory_latency.cpp && /tmp/memory_latency
python3 ssd_latency.py      # writes a 1 GiB file in /code, then deletes it
lscpu; free -h; df -h /

Part 3第 3 部分A node is a processnode 就是一個 process

A program is a file; a process is a program running程式是檔案;process 是正在跑的程式

driver.py is a file on the SSD. So is /usr/bin/python3, the program that runs it, and so are the ROS libraries it uses. To run a program, the kernel copies it from the SSD into RAM (Part 2 showed why) and gives it a core to run on. The running program, together with everything the kernel keeps track of for it, is a process.

driver.py 是 SSD 上的一個檔案。跑它的程式 /usr/bin/python3 也是,它用到的 ROS 函式庫也是。要跑一個程式,核心會把它從 SSD 複製到 RAM(第 2 部分說明了為什麼),再給它一個核心去跑。正在跑的程式,加上核心為它記錄的一切,就是 process。

SSD · files SSD · 檔案 kept when the power is off 斷電後還在 /usr/bin/python3 /code/driver.py /opt/ros/…/librcl.so exec load into memory 載入 記憶體 RAM · processes RAM · process emptied at power off 斷電就清空 process 39 · parent 36 process 39 · 父 process 36 code: python3 + driver.py + libraries 程式碼:python3 + driver.py + 函式庫 open files: /tmp/mcu, sockets, … 開著的檔案:/tmp/mcu、socket… 11 threads · 52 MB of RAM 11 條執行緒 · 52 MB RAM runs as: root (user 0) 身分:root(使用者 0)
One program file can become many processes; each process has its own number, parent, memory and open files. The numbers are from /proc/39/status below.同一個程式檔可以變成很多個 process;每個 process 都有自己的編號、父 process、記憶體和開著的檔案。數字來自下面的 /proc/39/status。

The kernel gives every process a number, the PID (process ID). Every node is one process, with its own PID. Two nodes in one launch are two processes; the same node started twice is two processes, too.

核心給每個 process 一個編號:PID(process ID)。每個 node 都是一個 process,有自己的 PID。一個 launch 裡的兩個 node 是兩個 process;同一個 node 啟動兩次,也是兩個 process。

What a shell isshell 是什麼

When you open a terminal, the window only shows text. The program you are actually typing to is a shell, usually bash. A shell does one job, over and over: read a command, start the program you named, wait until it finishes, then show the prompt ($) again. The shell is a process, and so is every program it starts for you.

打開終端機時,那個視窗只負責顯示文字。你真正在對它打字的程式叫 shell,通常是 bash。shell 一直重複做一件事:讀一個指令、啟動你指定的程式、等它結束,然後再顯示提示字元($)。shell 是一個 process,它幫你啟動的每個程式也都是。

Every process has a parent每個 process 都有父 process

A process never appears out of nothing: another process starts it, and that one is its parent. Linux does this in two steps, and it is easiest to see in code. Here is everything a shell does with one command, in C. The command is fixed to ps, which lists processes:

process 不會憑空出現:一定是另一個 process 啟動它,那個 process 就是它的父 process(parent)。Linux 分兩步完成這件事,用程式碼看最清楚。下面是 shell 處理一個指令時做的全部事情,用 C 寫的。指令固定是 ps:列出 process 的程式。

    printf("parent: I am PID %d\n", getpid());

    pid_t child = fork();

    if (child == 0) {
        printf("child:  I am PID %d, my parent is PID %d\n",
               getpid(), getppid());
        execlp("ps", "ps", "-o", "pid,ppid,cmd", NULL);
        perror("exec failed");
        return 1;
    }

    waitpid(child, NULL, 0);
    printf("parent: child %d has ended, back to me\n", child);

Point at a highlighted line to see a note. The whole file is code/tiny_shell.c.

把滑鼠移到標起來的那幾行,可以看到說明。完整檔案在 code/tiny_shell.c。

We compiled it and ran it from bash:

我們把它編譯好,在 bash 裡執行:

$ gcc -o tiny_shell /code/tiny_shell.c && ./tiny_shell
parent: I am PID 27
child:  I am PID 28, my parent is PID 27
    PID    PPID CMD
     20      13 bash --norc -i
     27      20 ./tiny_shell
     28      27 ps -o pid,ppid,cmd
parent: child 28 has ended, back to me

Follow the numbers. bash (PID 20) started tiny_shell (27). fork made a copy, 28, whose parent is 27. In the copy, exec replaced the program with ps, but the process stayed the same: ps lists itself as PID 28. The parent waited, and printed its last line only after the child had ended.

跟著數字看。bash(PID 20)啟動了 tiny_shell(27)。fork 複製出一份 28,它的父 process 是 27。在複製出來的那份裡,exec 把程式換成 ps,但 process 還是同一個:ps 列出的自己就是 PID 28。父 process 一直在等,等子 process 結束後才印出最後一行。

Step步驟What it does做什麼PID
forkcopy this process複製這個 processthe copy gets a new PID; its parent is the original複製出來的那份拿到新的 PID;它的父 process 是原本那個
execrun another program in this process在這個 process 裡改跑另一個程式unchanged不變
waitsleep until a child ends睡著,直到某個子 process 結束—

Every program you start from a terminal is started this way: the shell forks, the copy execs your program, and the shell waits. ros2 launch does the same once for every program in the launch file, except that it doesn't wait for one before starting the next: they run side by side. So processes form a tree, and ps --forest draws it:

你從終端機啟動的每個程式都是這樣啟動的:shell 先 fork,複製出來的那份 exec 你的程式,shell 再等它。ros2 launch 也一樣,對 launch 檔裡的每個程式各做一次,只是它不會等前一個結束才啟動下一個:它們同時在跑。所以 process 會排成一棵樹,ps --forest 會把它畫出來:

$ ps -e -o pid,ppid,cmd --forest
    PID    PPID CMD
     20      13  \_ bash --norc -i
     36      20  |   \_ /usr/bin/python3 .../bin/ros2 launch robot.launch.py
     37      36  |       \_ python3 /code/fake_mcu.py
     39      36  |       \_ python3 /code/driver.py
     41      36  |       \_ python3 /code/monitor.py

PPID is the parent's PID. bash (20) started the launcher (36), and the launcher started all three programs. The launcher is the parent of every node it starts. Remember that for Part 4.

PPID 是父 process 的 PID。bash(20)啟動了 launcher(36),launcher 再啟動了三個程式。launcher 是它啟動的每個 node 的父 process。第 4 部分會用到這件事。

Where the output goes: redirection and pipes輸出去哪裡:重新導向和 pipe

Between fork and exec, the shell sets up three numbered channels that every program starts with: 0, input (what you type), 1, output (the normal results), and 2, errors (error messages and warnings). Normally all three are your terminal. A few symbols tell the shell to connect them somewhere else, and the program never knows:

在 fork 和 exec 之間,shell 會幫新的 process 接好三個有編號的通道,每個程式一啟動就有:0 是輸入(你打的字),1 是輸出(正常的結果),2 是錯誤(錯誤訊息和警告)。平常三個都接到你的終端機。用幾個符號就能叫 shell 把它們接到別的地方,程式本身完全不知道:

You type你打的What happens會發生什麼
a > fileoutput (1) goes into file, replacing what was there輸出(1)寫進 file,蓋掉原本的內容
a >> fileoutput (1) is added to the end of file輸出(1)接在 file 的最後面
a &> fileoutput and errors go into file輸出和錯誤都寫進 file
a | ba pipe: the shell starts a and b together, and a's output (1) becomes b's input (0)pipe:shell 同時啟動 a 和 b,a 的輸出(1)變成 b 的輸入(0)
a |& ba pipe that carries a's output and errors把 a 的輸出和錯誤都送進去的 pipe

The & means "errors too". Scripts often spell the same thing out as > file 2>&1 and 2>&1 |; when you see those, read them as &> and |&.

& 的意思是「錯誤也一起」。腳本裡常把同一件事寫成比較長的 > file 2>&1 和 2>&1 |;看到它們時,就當成 &> 和 |&。

On its own: all three channels are the terminal 單獨跑:三個通道都是終端機 keyboard鍵盤 0 input0 輸入 ls 1 output1 輸出 2 errors2 錯誤 terminal終端機 A pipe joins one program's output to the next one's input pipe 把一個程式的輸出接到下一個的輸入 ps -e -o pid,cmd | grep driver ps 1 → pipe → 01 → pipe → 0 grep driver 1 terminal終端機 2 errors of both: still the terminal兩個的 2 錯誤:還是終端機

Output and errors are separate channels, so > catches only the output:

輸出和錯誤是分開的通道,所以 > 只接得到輸出:

$ ls /code/tiny_shell.c /nope > /tmp/out.txt
ls: cannot access '/nope': No such file or directory
$ cat /tmp/out.txt
/code/tiny_shell.c
$ ls /code/tiny_shell.c /nope &> /tmp/out.txt
$ cat /tmp/out.txt
ls: cannot access '/nope': No such file or directory
/code/tiny_shell.c

This matters for ROS, because a node writes its log to errors (2), not to output (1). Save a node's log with > alone, and the log stays on the screen while the file stays empty:

這對 ROS 很重要,因為 node 的 log 是寫到錯誤(2),不是輸出(1)。只用 > 存 node 的 log,log 會留在螢幕上,檔案卻是空的:

$ python3 monitor.py > /tmp/monitor.log     # Ctrl+C after two seconds
[INFO] [1795359247.531945339] [monitor]: ticks = None
[INFO] [1795359248.515822454] [monitor]: ticks = None
$ cat /tmp/monitor.log
$ python3 monitor.py &> /tmp/monitor.log     # nothing on the screen this time
$ head -2 /tmp/monitor.log
[INFO] [1795359863.838187073] [monitor]: ticks = None
[INFO] [1795359864.821016638] [monitor]: ticks = None

A pipe hands one program's output to the next. You have seen it with grep, which keeps only the lines that contain a word. Both programs run at the same time, so grep finds itself in the list too. (Part 5 writes grep [h]eartbeat to hide that line: the pattern still matches heartbeat, but grep's own command line no longer contains that word.)

pipe 把一個程式的輸出交給下一個。你看過它跟 grep 一起用:grep 只留下含某個字的行。兩個程式同時在跑,所以 grep 也會在清單裡找到它自己。(第 5 部分寫成 grep [h]eartbeat 來藏掉這一行:這個樣式還是會比對到 heartbeat,但 grep 自己的指令列裡已經沒有這個字了。)

$ ps -e -o pid,cmd | grep driver
     31 python3 /code/driver.py
     62 grep driver

To save a log and still watch it, pipe it into tee, which writes what it reads both to the screen and to a file. Use |&, so the errors go into the pipe too. This is the usual way to keep the log of a robot run:

想存 log 又想同時看到,就 pipe 給 tee:它把讀到的東西同時寫到螢幕和檔案。用 |&,錯誤才會一起進 pipe。這是保存機器人執行 log 最常見的做法:

$ ros2 launch robot.launch.py |& tee /tmp/run.log
[INFO] [launch]: All log files can be found below /root/.ros/log/2026-11-22-15-04-25-278690-91aa42cbd368-39
[INFO] [launch]: Default logging verbosity is set to INFO
[INFO] [python3-1]: process started with pid [41]
[python3-1] fake_mcu: /tmp/mcu -> /dev/pts/0
...
[python3-3] [INFO] [1795359868.434223491] [monitor]: ticks = 133
# Ctrl+C; every line above is also in /tmp/run.log
$ wc -l /tmp/run.log
9 /tmp/run.log

Over SSH there is no file manager, so two patterns do most of the finding. find searches a folder and everything inside it: -type f keeps only files, and -name takes a pattern in quotes, where * means "any characters". ls … | grep filters a listing, and grep takes a plain word, without *:

透過 SSH 沒有檔案總管可以用,大部分的「找東西」靠兩個寫法。find 會搜尋一個資料夾和裡面的所有東西:-type f 只留檔案,-name 接一個加引號的樣式,* 代表「任何字元」。ls … | grep 是過濾一份清單,grep 接的是一個單純的字,不加 *:

$ find /code -type f -name "*launch*"
/code/loop_driver.launch.py
/code/robot.launch.py
$ ls /opt/ros/humble/lib | grep rclcpp
librclcpp.so
librclcpp_action.so
librclcpp_lifecycle.so
rclcpp_components

On a robot, ls /dev | grep ACM finds the serial port of a USB board, such as ttyACM0.

在機器人上,ls /dev | grep ACM 可以找到 USB 板子的序列埠,例如 ttyACM0。

/proc: ask the kernel/proc:直接問核心

Where did ps get those PIDs and parents? From the kernel, which keeps a record of every process and shows it as files in /proc: one folder per PID.

ps 是從哪裡拿到這些 PID 和父 process 的?從核心。核心幫每個 process 留著紀錄,並把它當成檔案放在 /proc 裡:每個 PID 一個資料夾。

$ ls /proc     # only the numbered folders
1  7  13  20  36  37  39  41  ...
$ grep -E '^(State|PPid|VmRSS|Threads)' /proc/39/status
State:	S (sleeping)
PPid:	36
VmRSS:	   52932 kB
Threads:	11

The driver (39) is sleeping until its next timer, its parent is the launcher (36), it uses about 52 MB of RAM, and it runs 11 threads. These files are not on the SSD: the kernel writes them out at the moment you read them. ps and top do nothing more than read /proc. Part 8 shows more of it.

driver(39)在睡覺,等下一次 timer;它的父 process 是 launcher(36),用了大約 52 MB 的 RAM,有 11 條執行緒。這些檔案不在 SSD 上:是你讀的那一刻,核心才把它們寫出來。ps 和 top 做的也只是讀 /proc。第 8 部分有更多。

A container's processes are ordinary processes容器裡的 process 就是一般的 process

We ran all of this in a Docker container. A container is not a separate computer: its processes run on the same kernel as everything else, with their own view of the PIDs. On the host, outside the container, the same four processes show up with other numbers:

這些都是在 Docker 容器裡跑的。容器不是另一台電腦:它的 process 跟其他所有東西跑在同一個核心上,只是看到的 PID 不一樣。在主機上(容器外面),同樣四個 process 會用別的編號出現:

# inside the container
$ ps -eo pid,user,cmd
      1 root     /usr/bin/python3 /opt/ros/humble/bin/ros2 launch /code/robot.launch.py
     21 root     python3 /code/fake_mcu.py
     23 root     python3 /code/driver.py
     25 root     python3 /code/monitor.py
# on the host, at the same moment
$ ps -eo pid,user,cmd
  94385 root     /usr/bin/python3 /opt/ros/humble/bin/ros2 launch /code/robot.launch.py
  94466 root     python3 /code/fake_mcu.py
  94468 root     python3 /code/driver.py
  94470 root     python3 /code/monitor.py

So ps, /proc and kill work on the host too: the host can see and stop every container's processes. The container can only see its own.

所以 ps、/proc 和 kill 在主機上也能用:主機看得到、也停得掉每個容器的 process。容器只看得到自己的。

Part 4第 4 部分Stopping a process: signals停止 process:signal

Nothing outside a process can reach into it and stop it. Instead, the kernel delivers it a signal: a short notice with a number and a name. kill is the command that asks the kernel to send one; despite its name, it only sends a notice. These are the signals you will meet:

process 外面的東西沒辦法伸手進去把它停掉。取而代之的是,核心送給它一個 signal:一個帶編號和名字的簡短通知。kill 就是請核心送 signal 的指令;雖然叫 kill,它只是送一個通知。你會遇到的 signal 有這些:

SignalWhat sends it誰會送它Default action預設動作Can a process catch it?process 能接住嗎?
SIGINT (2)Ctrl+C in a terminal在終端機按 Ctrl+Cend the process結束 processyes可以
SIGTERM (15)kill PID; docker stop; a system shutting downkill PID;docker stop;系統關機end the process結束 processyes可以
SIGHUP (1)the terminal closes (an SSH session drops)終端機關掉(SSH 斷線)end the process結束 processyes可以
SIGKILL (9)kill -9 PIDend the process結束 processno: the kernel ends it at once不行:核心直接結束它

Every one of them ends the process by default. But a process can catch a signal: tell the kernel "when this one arrives, run my function instead". A node catches SIGINT to shut down cleanly. A launcher should catch it to stop its children first. Only SIGKILL can't be caught: the process never gets to run any code. Whether a signal is caught decides whether the process gets to clean up.

它們的預設動作都是結束 process。但 process 可以接住(catch)signal:告訴核心「這個 signal 到的時候,改跑我的函式」。node 接住 SIGINT 是為了好好地結束;launcher 應該接住它,先把子 process 停掉。只有 SIGKILL 接不住:process 連一行程式都沒機會跑。signal 有沒有被接住,決定了 process 有沒有機會收拾善後。

In ROS 2 Humble, ros2 launch catches SIGINT and nothing else. Now step through what kill did, and compare it with Ctrl+C:

在 ROS 2 Humble,ros2 launch 只接 SIGINT,其他都不接。現在一步一步看 kill 做了什麼,再跟 Ctrl+C 比較:

W1
Walkthrough 1: Two ways to stop a launch. Watch the process tree while T2 runs kill on the launcher, then replay with Ctrl+C in T1. Every PID and log line is from a real run. 逐步解說 1:停止 launch 的兩種方法。看著 process 樹:先在 T2 對 launcher 下 kill,再重來一次,改成在 T1 按 Ctrl+C。每個 PID 和每行 log 都來自真的執行結果。
Open walkthrough 1 ▶開啟逐步解說 1 ▶ 11 steps · ← → or a clicker · E for the explanation · L for 中文11 步 · ← → 或簡報筆 · E 看說明 · L 切換語言

So the answer to Part 1: kill 471 sent SIGTERM to the launcher alone. The launcher doesn't catch SIGTERM, so it ended at once, without telling its children. A process whose parent dies is an orphan, and the kernel gives it a new parent, PID 1, instead of stopping it. PID 1 is the first process of the system (or of the container), and it adopts every orphan. The nodes never received any signal, so they kept running.

所以第 1 部分的答案是:kill 471 只把 SIGTERM 送給 launcher。launcher 沒接 SIGTERM,所以立刻結束,沒有通知它的子 process。父 process 死掉的 process 叫做孤兒(orphan),核心不會停掉它,而是給它一個新的父 process:PID 1。PID 1 是系統(或容器)的第一個 process,所有孤兒都由它收養。node 從頭到尾沒收到任何 signal,所以繼續跑。

Ctrl+C works because of process groups. The shell puts a command and everything it starts into one group, and makes it the terminal's foreground group. Ctrl+C sends SIGINT to every process in that group at once, so each node gets the signal itself, and each one catches it.

Ctrl+C 有用,是因為 process group。shell 會把一個指令以及它啟動的所有東西放進同一個 group,並設成終端機的前景 group。Ctrl+C 會同時把 SIGINT 送給這個 group 裡的每個 process,所以每個 node 都親自收到 signal,而且每個都接住了。

When a process doesn't stopprocess 不肯停的時候

Ctrl+C only works if each node lets the signal end it, and that is easy to break by accident. Here is the driver written another common way, loop_driver.py: a plain loop instead of a timer and spin(), with a bare except: to skip a garbled line:

Ctrl+C 有用的前提是每個 node 都讓 signal 結束它,而這很容易不小心弄壞。這是用另一種常見寫法寫的 driver:loop_driver.py。它用一般的迴圈,而不是 timer 加 spin(),再用一個沒寫型別的 except: 跳過亂掉的資料:

while True:
    try:
        word, n = dev.readline().decode().split()   # e.g. "ticks 42"
        pub.publish(Int64(data=int(n)))
    except:                                          # skip a garbled line
        pass

It works fine until you stop it. In Python, Ctrl+C arrives as an exception, KeyboardInterrupt, and the bare except: catches that too, so the loop just goes on. This is what ros2 launch loop_driver.launch.py does after Ctrl+C (seconds since Ctrl+C on the left):

在你要停掉它之前,一切正常。在 Python 裡,Ctrl+C 會以例外 KeyboardInterrupt 的形式出現,而沒寫型別的 except: 連它也接住了,所以迴圈照樣繼續。這是按下 Ctrl+C 之後,ros2 launch loop_driver.launch.py 做了什麼(左邊是按下 Ctrl+C 後的秒數):

 0.0  ^C[WARNING] [launch]: user interrupted with ctrl-c (SIGINT)
 0.0  [ERROR] [python3-1]: process has died [pid 25, exit code -2, cmd 'python3 /code/fake_mcu.py'].
 5.0  [ERROR] [python3-2]: process[python3-2] failed to terminate '5' seconds after receiving 'SIGINT', escalating to 'SIGTERM'
 5.0  [INFO] [python3-2]: sending signal 'SIGTERM' to process[python3-2]
10.0  [ERROR] [python3-2]: process[python3-2] failed to terminate '10.0' seconds after receiving 'SIGTERM', escalating to 'SIGKILL'
10.0  [INFO] [python3-2]: sending signal 'SIGKILL' to process[python3-2]
10.0  [ERROR] [python3-2]: process has died [pid 27, exit code -9, cmd 'python3 /code/loop_driver.py'].

Ask politely, then firmly, then end it: SIGINT, SIGTERM after 5 s, SIGKILL after 5 s more. SIGKILL is the last resort, not the first. A process killed with SIGKILL can't close files, release a device or tell anyone it left, and Part 5 shows what that leaves behind. The exit code tells you how it ended: −9 means "ended by signal 9".

先客氣地問,再強硬地要求,最後直接結束:SIGINT,5 秒後 SIGTERM,再 5 秒後 SIGKILL。SIGKILL 是最後手段,不是第一個選擇。被 SIGKILL 結束的 process 沒辦法關檔案、釋放裝置,也沒辦法通知別人它離開了;第 5 部分會看到這會留下什麼。exit code 告訴你它怎麼結束的:−9 代表「被 signal 9 結束」。

The fix is one word: catch only what you expect, except ValueError: (what a garbled line raises). With that change, the same Ctrl+C stops the driver at once, with exit code −2. Better still, use a timer and spin(), as driver.py does.

修正只要加一個字:只接你預期會發生的例外,except ValueError:(亂掉的資料會丟出的例外)。改了之後,同樣的 Ctrl+C 會讓 driver 立刻結束,exit code 是 −2。更好的做法是像 driver.py 那樣用 timer 加 spin()。

On a robot在機器人上
Why does docker stop take 10 seconds?為什麼 docker stop 要 10 秒?

On a robot, nobody types ros2 launch by hand. The launch is written into the container's setup, often a compose file, as the container's command: the program Docker runs when the container starts. Ours, code/compose.yaml:

在機器人上,沒有人會手打 ros2 launch。launch 會寫在容器的設定裡(通常是 compose 檔),當成容器的 command:容器啟動時 Docker 要跑的程式。我們的 code/compose.yaml:

services:
  robot:
    image: dit-course
    volumes:
      - ./:/code
    command: ros2 launch /code/robot.launch.py

A container starts with no processes at all, so the command becomes its very first process, PID 1. There is no shell above it this time:

容器一開始一個 process 都沒有,所以這個 command 就成了它的第一個 process:PID 1。這次它上面沒有 shell:

$ docker compose up -d
$ docker compose exec robot ps -e -o pid,ppid,cmd
    PID    PPID CMD
      1       0 /usr/bin/python3 /opt/ros/humble/bin/ros2 launch /code/robot.launch.py
     14       1 python3 /code/fake_mcu.py
     16       1 python3 /code/driver.py
     18       1 python3 /code/monitor.py

docker stop (or docker compose stop) sends SIGTERM to PID 1, waits 10 s, then sends SIGKILL to everything. The launcher doesn't catch SIGTERM. In Part 1 that ended it at once; but PID 1 is special: a signal that PID 1 doesn't catch is simply ignored. So nothing happens for 10 s, and then every node is SIGKILLed without any chance to clean up:

docker stop(或 docker compose stop)會送 SIGTERM 給 PID 1,等 10 秒,再對所有東西送 SIGKILL。launcher 不接 SIGTERM。在第 1 部分,這讓它立刻結束;但 PID 1 很特別:PID 1 沒接的 signal 會直接被忽略。所以 10 秒內什麼事都沒發生,接著每個 node 都被 SIGKILL,完全沒機會收拾:

$ time docker compose stop
real	0m10.258s

The fix is one line in the compose file, stop_signal: SIGINT: Docker then sends the signal the launcher does catch, as if you pressed Ctrl+C. The launcher stops every node cleanly, each with exit code −2:

修正只要在 compose 檔加一行 stop_signal: SIGINT:Docker 就會改送 launcher 會接的 signal,就像你按了 Ctrl+C。launcher 會好好地停掉每個 node,每個的 exit code 都是 −2:

$ time docker compose stop      # with stop_signal: SIGINT
real	0m0.310s

(In a Dockerfile, the same setting is STOPSIGNAL SIGINT.)

(在 Dockerfile 裡,同樣的設定是 STOPSIGNAL SIGINT。)

Try it動手試
Make orphans, then stop a launch properly製造孤兒,再好好地停掉 launch

Start T1 as in Before the session, and run the launch in it:

照上課前的步驟開 T1,在裡面跑 launch:

docker run -it --rm --name os1 -v "$PWD/os-1/code":/code dit-course bash
cd /code && ros2 launch robot.launch.py

Open T2 with docker exec -it os1 bash. Before each step, say what you expect.

用 docker exec -it os1 bash 開 T2。每一步之前,先說出你預期會怎樣。

  1. In T2: ps -e -o pid,ppid,cmd --forest. Find the launcher's PID.在 T2:ps -e -o pid,ppid,cmd --forest。找到 launcher 的 PID。
  2. kill the launcher. Run ros2 node list and ps again. Who is the parent now?kill launcher。再跑一次 ros2 node list 和 ps。現在誰是父 process?
  3. Stop the orphans by PID. Start the launch again in T1 and stop it with Ctrl+C. Read the exit codes in the log.用 PID 停掉孤兒。在 T1 重新啟動 launch,用 Ctrl+C 停掉。讀 log 裡的 exit code。
  4. Run ros2 launch loop_driver.launch.py and press Ctrl+C. Count the seconds until the prompt comes back. Then change except: to except ValueError: and try again.跑 ros2 launch loop_driver.launch.py,按 Ctrl+C。數一數過幾秒才回到提示字元。接著把 except: 改成 except ValueError:,再試一次。

Part 5第 5 部分Daemons: processes with no terminaldaemon:沒有終端機的 process

When the SSH session dropsSSH 斷線的時候

On a robot you usually work over SSH: your terminal is on your laptop, and the shell runs on the robot. When the connection drops, from bad Wi‑Fi or a closed laptop lid, the robot's side of the terminal disappears. The kernel then sends SIGHUP ("hang up") to the terminal's foreground process group: the launcher and every node in it. We did exactly that to a terminal running our launch. Five seconds later:

在機器人上,你通常透過 SSH 工作:終端機在你的筆電上,shell 在機器人上跑。連線一斷(Wi‑Fi 不好、筆電蓋上),機器人那一端的終端機就消失了。這時核心會送 SIGHUP(hang up,掛斷)給這個終端機的前景 process group:launcher 和裡面的每個 node。我們真的對一個正在跑 launch 的終端機這樣做。5 秒後:

$ ps -e -o pid,ppid,cmd | grep -e 'ros2 launch' -e 'python3 /code'
(nothing)

No orphans this time: every process got the signal, and the default action for SIGHUP is to end. That is clean, but it is rarely what you want. A test run, a long recording or a match strategy you started over SSH dies with your Wi‑Fi. To survive, a process must not belong to your terminal at all.

這次沒有孤兒:每個 process 都收到了 signal,而 SIGHUP 的預設動作就是結束。乾淨是乾淨,但很少是你要的。透過 SSH 啟動的測試、長時間的錄製,或比賽策略,都會跟著你的 Wi‑Fi 一起死掉。要活下來,process 就不能屬於你的終端機。

Going to the background跑到背景去

A daemon is a program that runs in the background, with no terminal, until something stops it.

daemon 是在背景跑、沒有終端機、直到有東西停掉它才結束的程式。

A terminal, or tty (from "teletype", the typewriter-like machines early Unix ran on), is the device a program reads your keys from and prints its text to. Each terminal window or SSH login gets its own, named /dev/pts/0, /dev/pts/1, …, and ps shows it in the tty column. When you press Ctrl+C, the terminal itself turns the key into SIGINT and sends it out.

終端機,又叫 tty(來自 teletype:早期 Unix 用的那種像打字機的機器),是程式讀取你的按鍵、印出文字的裝置。每個終端機視窗或 SSH 登入都有自己的一個,名字是 /dev/pts/0、/dev/pts/1…,ps 把它顯示在 tty 欄。你按 Ctrl+C 時,是終端機自己把這個按鍵變成 SIGINT 送出去。

A program turns itself into a daemon in two steps. heartbeat.c is a tiny daemon: after the two steps, it writes one line a second to a log file, forever.

程式只要兩步就能把自己變成 daemon。heartbeat.c 是一個很小的 daemon:做完這兩步後,它每秒寫一行到 log 檔,永遠不停。

int main(void) {
    // 1. Fork, and the parent exits: your prompt comes back at once,
    //    and the child carries on in the background.
    if (fork() != 0) return 0;

    // 2. Cut the child's tie to the terminal: Ctrl+C and a hang-up can't reach it any more.
    setsid();

    // The daemon's work: one line a second.
    FILE *log = fopen("/tmp/heartbeat.log", "a");
    for (int i = 1; ; i++) {
        fprintf(log, "beat %d\n", i);
        fflush(log);
        sleep(1);
    }
}

The whole file is code/heartbeat.c.

完整檔案在 code/heartbeat.c。

$ gcc -o heartbeat /code/heartbeat.c && ./heartbeat
$                                     # the prompt is back at once
$ ps -e -o pid,ppid,tty,cmd | grep [h]eartbeat
     32       1 ?        ./heartbeat
$ exit                                # close the terminal
# a few seconds later, in a new terminal
$ ps -e -o pid,ppid,tty,cmd | grep [h]eartbeat
     32       1 ?        ./heartbeat
$ tail -n 2 /tmp/heartbeat.log
beat 5
beat 6
$ kill 32
tied to your terminal (pts/0)綁在你的終端機上(pts/0) Ctrl+C and hang-ups reach itCtrl+C 和掛斷會送到這裡 background: no terminal背景:沒有終端機 nothing on a terminal can reach it終端機上的事都碰不到它 start開始 1. fork, parent exits1. fork,父 process 結束 2. setsid()2. setsid() 25 · shell25 · shell ./heartbeat./heartbeat parent 25父 process 25 fork() 32 · child32 · 子 process parent 1 (adopted)父 process 1(被收養) ✕ the parent exited: prompt is back✕ 父 process 結束:提示字元回來了 setsid() 32 · the daemon32 · daemon parent 1 · tty ?父 process 1 · tty ? writes a beat every second每秒寫一行 beat
The run above, step by step.上面那次執行,一步一步畫出來。
  1. Fork, the parent exits. Your shell waits for the program it started (Part 3). That program ends at once, so you get your prompt back, while its child keeps going. Like any orphan, the child is adopted by PID 1.fork,父 process 結束。shell 會等它啟動的程式結束(第 3 部分)。那個程式馬上就結束了,所以提示字元立刻回來,而它的子 process 繼續跑。跟所有孤兒一樣,子 process 由 PID 1 收養。
  2. setsid(). The child cuts its tie to the terminal. From then on, nothing that happens on that terminal reaches it: not Ctrl+C, not a hang‑up, not closing the window.setsid()。子 process 切斷跟終端機的關係。從此終端機上發生的事都碰不到它:Ctrl+C、掛斷、關掉視窗都一樣。

The daemon is 32: parent 1, and ? in the tty column, which means no terminal. It kept writing after its terminal was gone, and only kill stopped it. Every daemon looks like this in ps: tty is ?, and the parent is usually 1. Real daemons usually do a little more, such as forking a second time and closing their terminal input and output; look up "double fork" if you are curious.

daemon 是 32:父 process 是 1,tty 欄是 ?,意思是沒有終端機。終端機不見了它還繼續寫,最後只有 kill 停得了它。每個 daemon 在 ps 裡都長這樣:tty 是 ?,父 process 通常是 1。真正的 daemon 通常還會多做一點,例如再 fork 一次、關掉終端機的輸入和輸出;有興趣可以查「double fork」。

Daemons you will meet你會遇到的 daemon

Here is one from the container we used for the launch:

這是我們跑 launch 的那個容器裡的一個:

$ ps -e -o pid,ppid,tty,cmd     # one line of it
    PID    PPID TT       CMD
     86       1 ?        /usr/bin/python3 -c from ros2cli.daemon.daemonize import main; main() --name ros2-daemon ...

That is the ROS 2 daemon, started the first time you ran a ros2 command. These are the daemons you will meet most:

那是 ROS 2 daemon,在你第一次執行 ros2 指令時就啟動了。你最常遇到的是這幾個 daemon:

DaemonWhat it does做什麼How to look at it怎麼查看它
tmux servertmux serverholds terminals that survive when you disconnect保管斷線後還活著的終端機tmux ls
ROS 2 daemonROS 2 daemonremembers which nodes and topics exist, so ros2 commands answer fast記住有哪些 node 和 topic,讓 ros2 指令回答得快ros2 daemon status
Docker daemon (dockerd)Docker daemon(dockerd)creates and runs containers; the docker command only sends it requests建立並執行容器;docker 指令只是送請求給它systemctl status docker

tmux: a terminal that belongs to a daemontmux:屬於 daemon 的終端機

tmux splits into two processes: a client that draws on your screen, and a server, a daemon, that owns the terminals your programs run in. Here we started the launch inside tmux, then dropped the connection the same way as above:

tmux 分成兩個 process:在你螢幕上畫東西的 client,以及 server:一個 daemon,擁有你的程式在裡面跑的終端機。這裡我們在 tmux 裡啟動 launch,然後用跟上面一樣的方式切斷連線:

# before
    PID    PPID TT       CMD
    349     343 pts/0     \_ bash --norc -i
    350     349 pts/0     |   \_ tmux new -s robot
    352       1 ?        tmux new -s robot
    353     352 pts/1     \_ -bash
    381     353 pts/1         \_ /usr/bin/python3 /opt/ros/humble/bin/ros2 launch robot.launch.py
    382     381 pts/1             \_ python3 /code/fake_mcu.py
    384     381 pts/1             \_ python3 /code/driver.py
    386     381 pts/1             \_ python3 /code/monitor.py
# after the connection dropped
    352       1 ?        tmux new -s robot
    353     352 pts/1     \_ -bash
    381     353 pts/1         \_ /usr/bin/python3 /opt/ros/humble/bin/ros2 launch robot.launch.py
    382     381 pts/1             \_ python3 /code/fake_mcu.py
    384     381 pts/1             \_ python3 /code/driver.py
    386     381 pts/1             \_ python3 /code/monitor.py
$ tmux ls
robot: 1 windows (created Fri Nov 20 09:36:01 2026)

There are two tmux processes. 350, on pts/0 (your terminal), is the client. 352, with no terminal and parent 1, is the server: a daemon. After the drop, only the client died with pts/0. The launch runs on pts/1, a terminal owned by the tmux server, and that one never hung up. tmux works because your programs' terminal belongs to a daemon, not to your SSH session. Log in again and tmux attach -t robot to get it back on your screen.

有兩個 tmux process。350 在 pts/0(你的終端機)上,是 client。352 沒有終端機、父 process 是 1,是 server:一個 daemon。斷線後,只有 client 跟著 pts/0 一起死了。launch 跑在 pts/1 上,那是 tmux server 擁有的終端機,它從來沒有被掛斷。tmux 有用,是因為你的程式所在的終端機屬於一個 daemon,而不是你的 SSH 連線。重新登入後 tmux attach -t robot,就能把它叫回螢幕上。

tmux can also be scripted, which is how many teams start a whole robot with one command: a session with one window per program, each one still there to look at later.

tmux 也可以寫成腳本,很多隊伍就是這樣用一個指令啟動整台機器人:一個 session、每個程式一個視窗,之後每個都還能回去看。

# -d: start it detached, with no client
tmux new-session -d -s robot "ros2 launch robot.launch.py"
tmux ls                  # robot: 1 windows ...
# look at it; Ctrl+B then D leaves it running
tmux attach -t robot

The ROS 2 daemon remembersROS 2 daemon 會記住

Daemons keep state, and state can be out of date. Back to the orphans from Part 1: we stopped them with kill -9, which ends a process before it can tell anyone it left. Then:

daemon 會保存狀態,而狀態可能過時。回到第 1 部分的孤兒:我們用 kill -9 停掉它們,這會讓 process 在通知任何人之前就結束。接著:

$ ps -e -o pid,cmd | grep "python3 /code"
(nothing)
$ ros2 node list
/driver
/monitor
$ ros2 node list --no-daemon
(nothing)
# 20 s later
$ ros2 node list
(nothing)

ros2 node list asks the daemon, and the daemon still remembers two nodes that no longer exist. With --no-daemon, the command looks at the network itself and finds nothing. The daemon forgets a node when it hears it leave, or, if the node died without a word, after a timeout: about 20 s here. When ros2 node list disagrees with ps, believe ps. To reset the daemon: ros2 daemon stop; the next ros2 command starts a fresh one.

ros2 node list 是去問 daemon,而 daemon 還記得兩個已經不存在的 node。加上 --no-daemon,指令會自己去網路上看,結果什麼都沒有。daemon 聽到 node 離開時就會忘掉它;如果 node 一聲不吭就死了,就要等逾時,這裡大約 20 秒。當 ros2 node list 跟 ps 說的不一樣時,相信 ps。要重設 daemon:ros2 daemon stop,下一個 ros2 指令會啟動一個新的。

Containers are started by a daemon too容器也是由 daemon 啟動的

When you run docker run, your shell doesn't start the container. The docker command sends a request to the Docker daemon, which starts it. On the host, the container's first process has this parent:

你執行 docker run 時,啟動容器的不是你的 shell。docker 指令送一個請求給 Docker daemon,由它來啟動。在主機上,容器的第一個 process 的父 process 是:

    PID    PPID CMD
  95583   95558 sleep infinity
  95558       1 /usr/bin/containerd-shim-runc-v2 ...

95583 is the container's PID 1 (here it was sleep infinity), and its parent is containerd-shim, a helper of the Docker daemon, not your shell.

95583 是容器的 PID 1(這裡是 sleep infinity),它的父 process 是 containerd-shim:Docker daemon 的幫手,不是你的 shell。

So a container started with docker run -d doesn't belong to your terminal and survives a dropped SSH session, like a tmux session does. The same goes for a command you start with docker exec -it: its terminal is held by the Docker daemon, not by your SSH session. We closed the terminal of a docker exec -it client, and the command inside the container kept running. That sounds convenient, but it is a launch you can no longer see or Ctrl+C, and the next one you start will clash with it. Find it with ps inside the container and stop it, or start it in tmux in the first place, so you can get back to it.

所以用 docker run -d 啟動的容器不屬於你的終端機,SSH 斷線後還會活著,就跟 tmux session 一樣。用 docker exec -it 啟動的指令也一樣:它的終端機由 Docker daemon 保管,不屬於你的 SSH 連線。我們關掉一個 docker exec -it client 的終端機,容器裡的指令繼續在跑。聽起來很方便,但那是一個你再也看不到、也沒辦法按 Ctrl+C 的 launch,你下一次啟動的 launch 會跟它撞在一起。在容器裡用 ps 找到它並停掉,或一開始就在 tmux 裡啟動,這樣才回得去。

On a robot在機器人上
The process that owns the serial port佔著序列埠的 process

Robots often run a long-lived bridge between the robot computer and a microcontroller, such as the micro-ROS agent: one process that opens the serial device and keeps it open. If a second copy starts (a leftover orphan, or a launch started twice), two processes read the same port and each gets half the bytes: garbled messages, or a microcontroller that seems to disconnect at random. To see who has a device open, fuser -v lists every process using it:

機器人上常常有一個長時間執行的橋接程式,連接機器人電腦和微控制器,例如 micro-ROS agent:一個打開序列裝置、一直開著的 process。如果又啟動了第二份(留下來的孤兒,或 launch 啟動了兩次),兩個 process 讀同一個序列埠,各拿到一半的位元組:訊息亂掉,或微控制器看起來隨機斷線。要看是誰開著某個裝置,fuser -v 會列出所有在用它的 process:

$ fuser -v /dev/pts/1
                     USER        PID ACCESS COMMAND
/dev/pts/1:          root        491 F.... python3
                     root        493 f.... python3

Here that is fake_mcu (491, which created the port) and driver (493), as expected. A third line would be your problem.

這裡是 fake_mcu(491,建立這個序列埠的)和 driver(493),符合預期。如果出現第三行,那就是你的問題。

Try it動手試
Survive a dropped connection; catch a stale daemon撐過斷線;抓到過時的 daemon
  1. In T2: tmux new -s robot, then cd /code && ros2 launch robot.launch.py inside it. Close the T2 window entirely. In T1: tmux ls and ps -e -o pid,ppid,tty,cmd --forest. Then tmux attach -t robot.在 T2:tmux new -s robot,在裡面執行 cd /code && ros2 launch robot.launch.py。把 T2 整個視窗關掉。在 T1:tmux ls 和 ps -e -o pid,ppid,tty,cmd --forest。然後 tmux attach -t robot。
  2. With the launch running, fuser -v $(readlink /tmp/mcu). Which PIDs, and which programs are they?launch 還在跑時,執行 fuser -v $(readlink /tmp/mcu)。有哪些 PID?它們是哪些程式?
  3. From outside tmux, pkill -9 -f '^python3 /code/', then at once ros2 node list and ros2 node list --no-daemon. Repeat ros2 node list every few seconds until the nodes disappear.在 tmux 外面執行 pkill -9 -f '^python3 /code/',馬上接著 ros2 node list 和 ros2 node list --no-daemon。每隔幾秒重跑一次 ros2 node list,直到 node 消失。

Part 6第 6 部分Who may touch this file誰可以碰這個檔案

Every process runs as a user, and every file belongs to one user and one group. Before a process opens a file, the kernel compares the two. id shows who you are:

每個 process 都以某個使用者的身分執行,每個檔案都屬於一個使用者和一個群組。process 要開檔案之前,核心會比對這兩者。id 告訴你你是誰:

$ id
uid=1000(member) gid=1000(member) groups=1000(member)

uid is your user number, and groups lists every group you are in. User 0 is root, who passes every check. In our container, every process ran as root (Uid: 0 in /proc), which is why nothing has been refused so far.

uid 是你的使用者編號,groups 列出你所在的每個群組。使用者 0 是 root,所有檢查都會通過。在我們的容器裡,每個 process 都以 root 執行(/proc 裡的 Uid: 0),所以到目前為止都沒有被拒絕過。

Reading ls -l讀懂 ls -l

A device is a file too, with an owner and permissions like any other. Our serial port is /tmp/mcu. Plain ls -l shows that this name is only a shortcut (type l, a link) to the real device, and a link's own permissions are never checked. -L shows the device behind it:

裝置也是檔案,跟其他檔案一樣有擁有者和權限。我們的序列埠是 /tmp/mcu。直接 ls -l 會看到這個名字只是指向真正裝置的捷徑(類型 l,連結),而連結自己的權限從來不會被檢查。-L 顯示它背後的裝置:

$ ls -l /tmp/mcu
lrwxrwxrwx 1 root root 10 Nov 22 12:11 /tmp/mcu -> /dev/pts/0
$ ls -lL /tmp/mcu
crw-rw---- 1 root dialout 136, 0 Nov 22 12:11 /tmp/mcu
crw-rw----rootdialout
type: c a device, l a link, d a folder, - a file類型:c 裝置、l 連結、d 資料夾、- 檔案what the owner may do擁有者可以做的事what the group may do群組可以做的事what everyone else may do其他人可以做的事owner擁有者group群組

r is read, w is write, and - means no. (For a program, x means you may run it; for a folder, enter it.) The kernel uses the first set that applies to you: owner, else group, else everyone else. So this port is for root and the members of group dialout, and nobody else. That is exactly how a real USB serial port, such as /dev/ttyUSB0, looks on Linux. (Where a file shows its size, a device shows two numbers, 136, 0, that the kernel uses to find it. You can skip them.)

r 是讀、w 是寫,- 是不行。(對程式來說,x 是可以執行;對資料夾來說,是可以進去。)核心使用第一組適用於你的權限:擁有者,不是的話看群組,再不是就看其他人。所以這個序列埠只給 root 和 dialout 群組的成員用,其他人都不行。真正的 USB 序列埠在 Linux 上就長這樣,例如 /dev/ttyUSB0。(一般檔案顯示大小的地方,裝置顯示的是兩個數字 136, 0,是核心用來找到它的編號,可以跳過。)

Now run the driver as member, an ordinary user we added with useradd -m member. member is not root, and not in group dialout, so the last set applies: ---.

現在以 member 執行 driver,這是我們用 useradd -m member 加的一般使用者。member 不是 root,也不在 dialout 群組,所以適用最後一組:---。

$ su member -s /bin/bash -c "source /opt/ros/humble/setup.bash; python3 /code/driver.py"
...
  File "/code/driver.py", line 15, in __init__
    self.dev = open(DEVICE, 'rb', buffering=0)   # a device is opened like any file
PermissionError: [Errno 13] Permission denied: '/tmp/mcu'

The fix is not to run everything as root. Put the user in the group that is allowed:

解法不是什麼都用 root 跑,而是把使用者加進被允許的那個群組:

$ usermod -aG dialout member
$ id member
uid=1000(member) gid=1000(member) groups=1000(member),20(dialout)
$ su member -s /bin/bash -c "source /opt/ros/humble/setup.bash; python3 /code/driver.py"
[INFO] [driver]: reading /tmp/mcu

On your own Linux laptop, the fix for a USB serial port is the same: sudo usermod -aG dialout $USER, then log out and in again. A process gets its groups when it starts, so a shell that is already running doesn't have the new one.

在你自己的 Linux 筆電上,USB 序列埠的解法也一樣:sudo usermod -aG dialout $USER,然後登出再登入。process 在啟動時取得它的群組,已經在跑的 shell 不會有新的群組。

The build/ folder you can't delete刪不掉的 build/ 資料夾

A container usually runs as root. When it writes into a folder shared with your laptop, the files it creates belong to root on your laptop too, because a user is just a number and the kernel is shared. Here a container plays a build: it makes a folder and one file in it.

容器通常以 root 執行。當它寫入一個跟你筆電共用的資料夾時,它建立的檔案在你的筆電上也屬於 root,因為使用者只是一個編號,而核心是共用的。這裡用一個容器假裝在編譯:建一個資料夾,裡面放一個檔案。

$ docker run --rm -v "$PWD":/ws -w /ws dit-course \
    bash -c 'mkdir -p build/my_pkg && echo x > build/my_pkg/out.o'
$ ls -l build
drwxr-xr-x 2 root root 60 Nov 20 17:31 my_pkg
$ rm -r build
rm: cannot remove 'build/my_pkg/out.o': Permission denied
$ docker run --rm -u "$(id -u):$(id -g)" -v "$PWD":/ws -w /ws dit-course \
    bash -c 'mkdir -p build/my_pkg && echo x > build/my_pkg/out.o'
$ ls -l build
drwxr-xr-x 2 member member 60 Nov 20 17:31 my_pkg

With -u, the container runs as your user number, so its files are yours. This is why many compose files and Dockerfiles take a user ID as a setting. If it already happened, delete the folder from inside a container, as root.

加上 -u,容器就以你的使用者編號執行,它建立的檔案就是你的。這就是為什麼很多 compose 檔和 Dockerfile 都把使用者 ID 當成一個設定。如果已經發生了,就從容器裡面以 root 刪掉那個資料夾。

Our course container does this too. It runs as root (this Part needs root inside it, to add the user member), and -v shares your os-1/code folder with it. When the launch file ran in Part 1, Python left a folder of cached code there, __pycache__, and on a Linux laptop it belongs to root, just like build/:

我們的課程容器也會這樣。它以 root 執行(這個部分需要在容器裡當 root,才能新增使用者 member),而 -v 把你的 os-1/code 資料夾分享給它。第 1 部分跑 launch 檔時,Python 在那裡留下一個放快取程式碼的資料夾 __pycache__,在 Linux 筆電上它屬於 root,跟 build/ 一樣:

# on your laptop, at the top of the repository
$ ls -ld os-1/code/__pycache__
drwxr-xr-x 2 root root 4096 Nov 21 02:25 os-1/code/__pycache__
$ rm -r os-1/code/__pycache__
rm: cannot remove 'os-1/code/__pycache__/robot.launch.cpython-310.pyc': Permission denied
# inside the container, where you are root
$ rm -r /code/__pycache__
On a robot在機器人上
Privileged containers skip all of thisprivileged 容器跳過這一切

Robot containers are often started with privileged: true and the host's /dev mounted inside: every device is visible and every check passes, so serial ports, cameras and GPIO just work. The price is that the container can do anything to the robot computer: format a disk, load a kernel module, stop any process. That is a fair trade on a robot that only runs your code; it is a bad habit on a shared server. Knowing which check you are skipping helps when the same code moves somewhere stricter.

機器人的容器常常用 privileged: true 啟動,並把主機的 /dev 掛進去:每個裝置都看得到、每個檢查都會通過,所以序列埠、相機、GPIO 直接就能用。代價是容器可以對機器人電腦做任何事:格式化硬碟、載入核心模組、停掉任何 process。在只跑你自己程式的機器人上,這是合理的取捨;在共用的伺服器上,這是壞習慣。知道自己跳過了哪個檢查,同一份程式搬到比較嚴格的地方時才不會卡住。

Part 7第 7 部分Code you didn't compile不是你編譯的程式碼

Most of the code in a running node isn't yours. A C++ node is an executable, but much of its code sits in shared libraries (.so files): ROS's client library, the message types, DDS. They are separate files, found and loaded when the program starts, not when it is built. ldd lists what a program needs and where each one was found (in a shell that sourced ROS; three lines of many):

正在跑的 node 裡,大部分的程式碼都不是你的。C++ node 是一個執行檔,但它的很多程式碼放在共享函式庫(.so 檔)裡:ROS 的 client library、message 型別、DDS。它們是獨立的檔案,在程式啟動時才被找到並載入,而不是在編譯時。ldd 會列出一個程式需要什麼、各自在哪裡找到(在 source 過 ROS 的 shell 裡;節錄三行):

$ ldd install/my_pkg/lib/my_pkg/slow_server
	librclcpp.so => /opt/ros/humble/lib/librclcpp.so (0x000079963e2ee000)
	libexample_interfaces__rosidl_typesupport_cpp.so => /opt/ros/humble/lib/libexample_interfaces__rosidl_typesupport_cpp.so (0x000079963e2de000)
	libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x000079963de07000)

In a fresh shell where ROS was never sourced, the same program won't start:

在一個從沒 source 過 ROS 的新 shell 裡,同一個程式啟動不了:

$ ./slow_server
./slow_server: error while loading shared libraries: librclcpp.so: cannot open shared object file: No such file or directory
$ ldd ./slow_server | grep "not found"
	librclcpp.so => not found
	libexample_interfaces__rosidl_typesupport_cpp.so => not found
	librcl.so => not found

The fix is source /opt/ros/humble/setup.bash. Sourcing your workspace's install/setup.bash does it too, because it first sources the ROS it was built with. (install/local_setup.bash doesn't: it adds only your own packages, so the libraries above stay missing.)

解法是 source /opt/ros/humble/setup.bash。source 你 workspace 的 install/setup.bash 也可以,因為它會先 source 建置時用的那個 ROS。(install/local_setup.bash 不會:它只加你自己的套件,上面那些函式庫還是找不到。)

What source setup.bash really doessource setup.bash 到底做了什麼

It sets environment variables: settings that a process passes on to every process it starts. Three of them tell programs where to look:

它設定環境變數:process 會傳給它啟動的每個 process 的設定。其中三個告訴程式去哪裡找:

Variable變數Who reads it誰讀它For what找什麼
LD_LIBRARY_PATHthe loader, when any program starts載入器,在任何程式啟動時shared libraries (.so)共享函式庫(.so)
PYTHONPATHPythonPython packages, such as rclpyPython 套件,例如 rclpy
AMENT_PREFIX_PATHros2 commands and launchros2 指令和 launchROS packages: where ros2 run finds my_pkgROS 套件:ros2 run 去哪裡找 my_pkg

Each is a list of folders, searched in order. strace (Part 8) shows the loader doing exactly that while the driver starts: it tries the first folder of LD_LIBRARY_PATH, fails, and finds librcl.so in the second.

每一個都是資料夾的清單,依序搜尋。strace(第 8 部分)可以看到 driver 啟動時載入器正是這樣做的:先試 LD_LIBRARY_PATH 的第一個資料夾,找不到,再在第二個找到 librcl.so。

$ echo $LD_LIBRARY_PATH
/opt/ros/humble/lib/x86_64-linux-gnu:/opt/ros/humble/lib
$ strace -f -e trace=openat python3 driver.py         # (two lines of many)
openat(AT_FDCWD, "/opt/ros/humble/lib/x86_64-linux-gnu/librcl.so", O_RDONLY|O_CLOEXEC) = -1 ENOENT (No such file or directory)
openat(AT_FDCWD, "/opt/ros/humble/lib/librcl.so", O_RDONLY|O_CLOEXEC) = 3

Underlay and overlay: the first match winsunderlay 和 overlay:第一個找到的贏

ROS itself, in /opt/ros/humble, is the underlay. Your workspace, built with colcon, is an overlay on top of it. Sourcing the overlay puts its folders in front of the underlay's:

ROS 本身(/opt/ros/humble)是 underlay。你用 colcon 建的 workspace 是疊在它上面的 overlay。source overlay 會把它的資料夾放在 underlay 的前面:

$ source /opt/ros/humble/setup.bash
$ ros2 pkg prefix my_pkg
Package not found
$ source ~/tutorial_ws/install/setup.bash
$ ros2 pkg prefix my_pkg
/root/tutorial_ws/install/my_pkg
$ echo $AMENT_PREFIX_PATH
/root/tutorial_ws/install/my_pkg:/opt/ros/humble

Because the search stops at the first match, which version of a package you run depends on what was sourced, and in which order. If a package exists in two workspaces, the one sourced last is in front. And a terminal keeps the variables from when you sourced: a terminal opened before a rebuild, or one that sourced another workspace, can run a different version from the one you just built. When "the change didn't do anything", check ros2 pkg prefix before you check your code.

因為搜尋在第一個找到時就停,你跑的是套件的哪個版本,取決於 source 了什麼、以什麼順序。如果一個套件存在於兩個 workspace,最後 source 的那個排在前面。而終端機會保留你 source 當時的變數:在重新編譯前就開著的終端機,或 source 了別的 workspace 的終端機,跑的版本可能跟你剛建好的不一樣。遇到「改了卻沒效果」時,先查 ros2 pkg prefix,再查你的程式。

When to source again什麼時候要重新 source

Sourcing your workspace adds one folder per package to these lists: install/my_pkg, install/other_pkg, and so on. Sourcing it again doesn't add them twice: the script removes a folder before it adds it. So you need to source again only when a new package folder appears, or in a new terminal. A changed file needs colcon build instead: a normal build copies your files into install/, and the copy is what runs.

source 你的 workspace,會把每個套件的一個資料夾加進這些清單:install/my_pkg、install/other_pkg 等等。再 source 一次不會加兩次:腳本會先把資料夾拿掉再加回去。所以只有出現新的套件資料夾,或開了新的終端機時,才需要重新 source。改了檔案要做的是 colcon build:一般的 build 會把你的檔案複製到 install/,真正被執行的是那份複本。

What changed改了什麼colcon build?Source again?重新 source?
Code in a package you already built已經建過的套件裡的程式碼yes要no不用
A new node in that package那個套件裡多一個新的 nodeyes要no不用
A new package一個新的套件yes要yes: its folder in install/ is new要:它在 install/ 裡的資料夾是新的
Nothing, but you opened a new terminal什麼都沒改,但開了新的終端機no不用yes: a new terminal starts without the variables要:新的終端機一開始沒有這些變數
Python code, built with colcon build --symlink-installPython 程式碼,用 colcon build --symlink-install 建的no: install/ links to your files instead of copying them不用:install/ 連結到你的檔案,而不是複製它們no不用

Forget to source after adding a package, and ROS can't find it, even though it built fine:

加了新套件卻忘了 source,ROS 就找不到它,即使它建置成功:

$ colcon build                  # pkg_b is a new package
Summary: 2 packages finished [0.96s]
$ ros2 run pkg_b hi
Package 'pkg_b' not found
$ source install/setup.bash
$ ros2 run pkg_b hi
Hi from pkg_b.

Plugins: loaded by name, at run timeplugin:在執行時依名字載入

Some libraries aren't listed by ldd at all. A plugin is a shared library that a program loads while running, because a parameter or a configuration file names it. Navigation stacks choose their planner and controller this way, and ros2_control loads hardware drivers this way. The program was built without knowing the plugin exists, so a missing or broken plugin shows up only when the program runs: a message such as "failed to load plugin" or "undefined symbol" in the log, often from a plugin built against a different version of its library. The checks are the same as above: is the package found (ros2 pkg prefix), and was it built in the workspace you sourced?

有些函式庫根本不會出現在 ldd 裡。plugin 是程式在執行中才載入的共享函式庫,因為某個參數或設定檔指名了它。導航系統就是這樣選擇它的 planner 和 controller,ros2_control 也是這樣載入硬體驅動。程式編譯時並不知道這個 plugin 存在,所以plugin 不見或壞掉,只有在程式執行時才會出現:log 裡出現 "failed to load plugin" 或 "undefined symbol" 之類的訊息,常常是因為 plugin 是對著另一個版本的函式庫編譯的。檢查方式跟上面一樣:找得到這個套件嗎(ros2 pkg prefix)?它是在你 source 的那個 workspace 裡建的嗎?

Try it動手試
Permission denied, then a missing librarypermission denied,然後是找不到函式庫
  1. In T2: python3 /code/fake_mcu.py &, then ls -l /tmp/mcu and ls -lL /tmp/mcu. Read the permissions aloud: who may read?在 T2:python3 /code/fake_mcu.py &,再 ls -l /tmp/mcu 和 ls -lL /tmp/mcu。把權限唸出來:誰可以讀?
  2. useradd -m member, then su member -s /bin/bash -c "source /opt/ros/humble/setup.bash; python3 /code/driver.py". Fix it with a group, without making member root.useradd -m member,再 su member -s /bin/bash -c "source /opt/ros/humble/setup.bash; python3 /code/driver.py"。用群組修好它,不要讓 member 變成 root。
  3. ldd ~/tutorial_ws/install/my_pkg/lib/my_pkg/slow_server. Then run the same program with env -i in front (an empty environment) and read the error.ldd ~/tutorial_ws/install/my_pkg/lib/my_pkg/slow_server。再在同一個程式前面加 env -i(空的環境)執行,讀錯誤訊息。

Part 8 · Go deeper第 8 部分 · 延伸Tools and details for later之後再看的工具和細節

Go deeper: zombies, and why docker run --init exists延伸:zombie,以及為什麼有 docker run --init read after the session課後再讀

When a process ends, the kernel keeps a small record of it, its exit code, until its parent reads it with wait(). Until then the process is a zombie: dead, but still in the table. The launcher's log line "process has died [..., exit code -2]" is the launcher reading that record. Orphans are adopted by PID 1, and a normal PID 1 (systemd, or tini in a container started with --init) reads their records too. But if PID 1 is a program that never calls wait(), zombies pile up. Our first test container ran sleep infinity as PID 1, and after a few experiments it looked like this:

process 結束時,核心會保留它的一小筆紀錄(exit code),直到它的父 process 用 wait() 讀走。在那之前,這個 process 是 zombie:已經死了,但還留在表裡。launcher 的 log「process has died [..., exit code -2]」就是 launcher 讀到了這筆紀錄。孤兒由 PID 1 收養,正常的 PID 1(systemd,或用 --init 啟動的容器裡的 tini)也會讀走它們的紀錄。但如果 PID 1 是一個從不呼叫 wait() 的程式,zombie 就會越積越多。我們第一個測試容器用 sleep infinity 當 PID 1,做了幾次實驗之後變成這樣:

    PID    PPID TT       CMD
    362       1 ?        [ros2] <defunct>
    363       1 ?        [python3] <defunct>
    365       1 ?        [python3] <defunct>
    367       1 ?        [python3] <defunct>
    ... 19 more

Zombies use no CPU or memory, only a PID each. But a container that runs for weeks can run out. docker run --init (or init: true in compose) puts a tiny PID 1 in front of your program that does nothing but pass signals on and read exit codes.

zombie 不用 CPU 也不用記憶體,只各佔一個 PID。但跑了好幾個禮拜的容器可能會用完。docker run --init(或 compose 裡的 init: true)會在你的程式前面放一個很小的 PID 1,它只做兩件事:把 signal 傳下去、讀走 exit code。

Go deeper: strace, watching a process talk to the kernel延伸:strace,看 process 跟核心對話 read after the session課後再讀

A process can't open a file, send a packet or start a child by itself; it asks the kernel with a system call. strace prints every system call a program makes. It is the tool to reach for when a program fails without saying why: which file did it try to open, and what did the kernel answer? Here the driver opens the serial port, and gets file number 15. Afterwards ls -l /proc/PID/fd lists it as 15 -> /dev/pts/1:

process 沒辦法自己開檔案、送封包或啟動子 process;它要透過系統呼叫(system call)請核心做。strace 會印出程式做的每個系統呼叫。當程式失敗卻不說原因時,就用它:它試著開哪個檔案?核心回答了什麼?這裡 driver 開啟序列埠,拿到檔案編號 15。之後 ls -l /proc/PID/fd 會把它列成 15 -> /dev/pts/1:

$ strace -f -e trace=openat python3 driver.py
...
[pid   532] openat(AT_FDCWD, "/tmp/mcu", O_RDONLY|O_CLOEXEC) = 15

It is already in the course container. -f follows threads and children; -e trace= picks which calls to show; -p PID attaches to a process that is already running.

課程容器裡已經裝好了。-f 會跟著執行緒和子 process;-e trace= 選擇要顯示哪些呼叫;-p PID 可以接上一個已經在跑的 process。

Go deeper: stable device names with udev rules延伸:用 udev rule 取得固定的裝置名稱 read after the session課後再讀

Plug in two USB serial adapters and they become /dev/ttyUSB0 and /dev/ttyUSB1, in whatever order they were detected, which can change at the next boot. udev is the daemon that creates device files when hardware appears, and a udev rule tells it to add a fixed name, a symlink, chosen by something unique to the device: its USB vendor and product ID, or its serial number. That is the same idea as our /tmp/mcu → /dev/pts/0. A rule can also set the group and mode, which solves Part 6 for that one device:

插上兩個 USB 序列轉接器,它們會變成 /dev/ttyUSB0 和 /dev/ttyUSB1,順序看偵測的先後,下次開機可能就不一樣。udev 是硬體出現時建立裝置檔的 daemon,而 udev rule 告訴它根據裝置獨有的東西(USB 廠商和產品 ID,或序號)加上一個固定的名字:一個 symlink。這跟我們的 /tmp/mcu → /dev/pts/0 是同一個概念。rule 也可以設定群組和權限,這樣就解決了那個裝置的第 6 部分問題:

# /etc/udev/rules.d/99-robot.rules  (the IDs are an example: read yours with `udevadm info /dev/ttyUSB0`)
SUBSYSTEM=="tty", ATTRS{idVendor}=="0483", ATTRS{idProduct}=="5740", SYMLINK+="mcu", GROUP="dialout", MODE="0660"

Reload with sudo udevadm control --reload && sudo udevadm trigger. Rules live on the host, not in the container: the host's udev creates /dev/mcu, and a container sees it if /dev is shared.

用 sudo udevadm control --reload && sudo udevadm trigger 重新載入。rule 放在主機上,不是容器裡:主機的 udev 建立 /dev/mcu,容器只要共用 /dev 就看得到。

Go deeper: permission bits as numbers延伸:用數字表示權限位元 read after the session課後再讀

Each rwx group is three bits: r = 4, w = 2, x = 1. So rw- is 6, r-x is 5, and crw-rw---- is mode 660. chmod 660 file sets all three groups at once; chmod g+rw file changes only what you name. There are three more bits, rarely needed: setuid (the program runs as its owner, which is how sudo becomes root), setgid, and the sticky bit (on /tmp: anyone may create files there, but only the owner may delete them).

每組 rwx 是三個位元:r = 4、w = 2、x = 1。所以 rw- 是 6,r-x 是 5,crw-rw---- 是權限 660。chmod 660 file 一次設定三組;chmod g+rw file 只改你指定的部分。另外還有三個很少用到的位元:setuid(程式以它的擁有者身分執行,sudo 就是這樣變成 root 的)、setgid,以及 sticky 位元(在 /tmp 上:任何人都能在裡面建檔案,但只有擁有者能刪除)。

Go deeper: starting software at boot with systemd延伸:用 systemd 在開機時啟動軟體 read after the session課後再讀

On most Linux computers, PID 1 is systemd. Besides adopting orphans, it starts daemons at boot, restarts them when they crash, and stops them in order at shutdown. Each daemon is described by a unit file. A robot that should start its software when it is switched on, with no one logging in, can use one:

在大部分 Linux 電腦上,PID 1 是 systemd。除了收養孤兒,它還在開機時啟動 daemon、在它們當掉時重新啟動、關機時依序停掉它們。每個 daemon 用一個 unit 檔描述。希望一開機、不用人登入就啟動軟體的機器人,可以用一個:

# /etc/systemd/system/robot.service  (an example)
[Unit]
Description=Robot stack
After=docker.service
Requires=docker.service

[Service]
ExecStart=/usr/bin/docker compose -f /home/robot/compose.yaml up
ExecStop=/usr/bin/docker compose -f /home/robot/compose.yaml down
Restart=on-failure

[Install]
WantedBy=multi-user.target

sudo systemctl enable --now robot starts it now and at every boot; systemctl status robot and journalctl -u robot show its state and output. When you stop it, systemd sends SIGTERM and, after a timeout, SIGKILL: the same story as Part 4.

sudo systemctl enable --now robot 會立刻啟動它,並在每次開機時啟動;systemctl status robot 和 journalctl -u robot 會顯示它的狀態和輸出。停止它時,systemd 會送 SIGTERM,逾時後再送 SIGKILL:跟第 4 部分是同一個故事。

Go deeper: top, and more of /proc延伸:top,以及更多 /proc read after the session課後再讀

top (or the friendlier htop) lists processes sorted by CPU use, live. Press H to see threads, and 1 to see each CPU core. A node at 100 % of one core is usually a loop that never sleeps. Every number in top comes from /proc, and there is more there: /proc/PID/environ holds the environment a process started with (useful to check which workspace it sourced: tr '\0' '\n' < /proc/PID/environ | grep AMENT), /proc/PID/maps lists every library it loaded, and /proc/cpuinfo and /proc/meminfo describe the machine. OS‑2 uses these to look at memory and threads.

top(或比較好用的 htop)會即時依 CPU 使用率列出 process。按 H 看執行緒,按 1 看每個 CPU 核心。一個佔滿一個核心 100 % 的 node,通常是一個從不 sleep 的迴圈。top 裡的每個數字都來自 /proc,而 /proc 裡還有更多:/proc/PID/environ 是 process 啟動時的環境變數(可以用來檢查它 source 了哪個 workspace:tr '\0' '\n' < /proc/PID/environ | grep AMENT),/proc/PID/maps 列出它載入的每個函式庫,/proc/cpuinfo 和 /proc/meminfo 描述這台機器。OS‑2 會用它們來看記憶體和執行緒。

More of what the kernel knows about one process (the driver, in another run):

核心對一個 process 還知道更多(driver,另一次執行):

$ tr '\0' ' ' < /proc/365/cmdline; readlink /proc/365/cwd /proc/365/exe
python3 /code/driver.py      # the command line it was started with
/code                        # its working folder
/usr/bin/python3.10          # the program file it runs
$ ls -l /proc/365/fd
lr-x------ 1 root root 64 Nov 20 09:29 0 -> pipe:[310979]
l-wx------ 1 root root 64 Nov 20 09:29 1 -> pipe:[310980]
lrwx------ 1 root root 64 Nov 20 09:29 10 -> socket:[306845]
lr-x------ 1 root root 64 Nov 20 09:29 11 -> /dev/shm/fastrtps_port7413_el
...

fd lists every open file by number. 0 and 1 are its input and output, connected to the launcher by pipes; the sockets and /dev/shm files are DDS talking to other nodes.

fd 依編號列出所有開著的檔案。0 和 1 是它的輸入和輸出,用 pipe 接到 launcher;socket 和 /dev/shm 的檔案是 DDS 在跟其他 node 溝通。

Take home帶回家What you can now explain你現在能解釋的事

Tick each one you could explain to a teammate without looking at this page.

不看這一頁也能跟隊友解釋清楚的,就打勾。

Attribution出處Credits致謝