使用fork()系统调用创建进程过程分析

1. 在menu/test.c中添加fork()调用源码:

int MyFork(int argc, char* argv[]) {
    // fork a new process
    int pid = 0;
    do {
        pid = fork();
    } while(pid < 0);
    if(pid == 0) {
        puts("This is the child process!");
        exit(0);
    } else {
        wait(NULL);
        puts("This is the parent process!");
    }
    return 0;
}

2. 在MenuOS中加入该命令(menu/test.c):

int main() {
     // ...
     MenuConfig(fork, "Fork a new process", MyFork);
    // ...   
}

3. 创建根文件系统:

make rootfs

4. 启动qemu跟踪fork()创建进程过程:

qemu -kernel linux-3.18.6/arch/x86/boot/bzImage -initrd rootfs.img -s -S

5. 在另起一个终端中启动gdb:

gdb

加载符号表、调试目标、设置断点、继续执行:

gdb> file linux-3.18.6/vmlinux
gdb> target remote:1234
gdb> b sys_clone
gdb> c

6. 在MenuOS命令行下输入fork执行MyFork函数:

MenuOS>> fork

在gdb命令行下添加断点:

gdb> do_fork
gdb> copy_process
gdb> trace_sched_process_fork
gdb> dup_task_struct
gdb> alloc_task_struct_node
gdb> arch_dup_task_struct
gdb> sched_fork gdb
> copy_files gdb> copy_fs gdb> copy_sighand gdb> copy_mm gdb> copy_io gdb> copy_thread
gdb> ret_from_fork

7. 输出结果:

MenuOs>> fork
This is the child process! This is the parent process!

8. 总结:

通过对fork()系统调用创建一个新进程过程的跟踪, 了解到Linux系统下进程是如何创建的。

原文地址:https://www.cnblogs.com/long3216/p/4420253.html