0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

GDBでfork後の親子プロセスのデバッグ【備忘録】

Last updated at Posted at 2025-05-17

サンプルコード

fork_debug.c
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>

int main() {
    pid_t pid;

    printf("Before fork\n");

    pid = fork();

    if (pid == 0) {
        // 子プロセス
        printf("This is the child process. PID: %d\n", getpid());
    } else if (pid > 0) {
        // 親プロセス
        printf("This is the parent process. PID: %d, child PID: %d\n", getpid(), pid);
    } else {
        // fork失敗
        perror("fork");
        return 1;
    }

    printf("Both processes continue from here.\n");

    return 0;
}

ビルド 〜 デバッグ開始

  • ビルドします
    -g オプションでデバッグ情報を埋め込みます。
bash
gcc -g -o fork_debug fork_debug.c
  • デバッガ(GDB)を起動します
bash
gdb ./fork_debug

追跡するプロセスの設定

  • set follow-fork-mode 機能 を使用して、fork後に親プロセスと子プロセスどちらのデバッグを実行するか設定します
bash
(gdb) set follow-fork-mode parent # 親プロセスをデバッグしたい場合
(gdb) set follow-fork-mode child  # 子プロセスをデバッグしたい場合
(gdb) break main
(gdb) run

  • ステップを実行していき、fork()がある行まで進めます
bash
(gdb) next                 # fork() に進む
(gdb) next                 # fork後の行へ。ここで分岐が発生
  • fork後は、デバッグしないプロセスが最後まで実行されてから、デバッグするプロセスに切り替わります。子プロセスをデバッグする場合、以下のように出力されます。(プロセスIDは環境によって変わります。)
bash
[Attaching after process 8299 fork to child process 9798]
[New inferior 2 (process 9798)]
[Detaching after fork from parent process 8299]
This is the parent process. PID: 8299, child PID: 9798
Both processes continue from here.
[Inferior 1 (process 8299) detached]
[Switching to process 9798]
main () at fork_debug.c:12
12          if (pid == 0) {
(gdb) info inferiors # GDBが現在管理しているプロセスの一覧を表示する
  Num  Description       Executable
  1    <null>            /workspace/fork_debug  # 親プロセスは既に完了しているため、管理対象外となっている
* 2    process 9798      /workspace/fork_debug # 子プロセス(Num左横の '*' は現在追跡しているプロセス)

以上、備忘録でした。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?