Upgrade to Pro — share decks privately, control downloads, hide ads and more …

その47 日常ソースコードリーディング pgrepの使い方を間違えたのをきっかけにLinuxカーネルのコードを読む

その47 日常ソースコードリーディング pgrepの使い方を間違えたのをきっかけにLinuxカーネルのコードを読む

以下動画のテキストです。
https://youtu.be/n34LCB7Iwig

Satoru Takeuchi

August 24, 2022
Tweet

More Decks by Satoru Takeuchi

Other Decks in Technology

Transcript

  1. 仕様を確認 • man pgrepより抜粋 NOTES The process name used for

    matching is limited to the 15 characters present in the output of /proc/pid/stat. Use the -f option to match against the complete command line, /proc/pid/cmdline. 5
  2. まずはprocfsのmanを確認 /proc/[pid]/stat Status information about the process. This is used

    by ps(1). It is defined in the kernel source file fs/proc/array.c. … (2) comm %s The filename of the executable, in parentheses. This is visible whether or not the executable is swapped out. 7
  3. task_struct.commに入る文字列 • 内容は実行ファイルパスの最後の”/”の後の部分 ◦ basenameコマンド実行結果とおなじ void setup_new_exec(struct linux_binprm * bprm)

    { … __set_task_comm(current, kbasename(bprm->filename), true); … include/linux/string.h fs/exec.c static inline const char *kbasename(const char *path) { const char *tail = strrchr(path, '/'); return tail ? tail + 1 : path; } 13
  4. task_struct.commの役割 • カーネル内から人間が読めるかたちでコマンド名を得たいときがある ◦ 例: dmesgにOOM killerで殺したプロセスの名前を出す • argvはページアウト(スワップアウト)している可能性がある ◦

    コマンド名参照のたびに毎度ページインさせてられない (そもそもできないこともある ) • かといってクソ長コマンド名をカーネル内にたくさんもつのも嫌 • いい落としどころがtask_struct.comm 物理メモリ argv カーネルのメモリ (ページング非対象) プロセスのメモリ (ページング対象) 15
  5. まとめ • pgrep ◦ デフォルトでカーネルが定義するところのコマンド名にマッチ ◦ コマンド名は/proc/<pid>/statファイルの第二フィールドの両端の ”(”と”)”を取ったもの ◦ プロセス起動に使った実行ファイル名の

    basenameの先頭15バイト ◦ -fオプションをつけると細かいマッチをさせられるが注意が必要 • そのほか ◦ ほんのちょっとしたきっかけでソースコードを読む機会は生まれる ◦ 目的があれば読むのが続く ◦ 土地勘のあるコードだと読むのが楽 ◦ 仕事だともっと厳密にやろうね! (pgrepのソースも見るとか) 16