Linux进程创建
Linux进程创建 准备 以fork函数为例,看下Linux进程创建具体工作流程: 下面是使用fork函数创建进程的一段C代码: #include <sys/wait.h> #include <stdio.h> #include <stdlib.h> int main (int argc, char *argv[]) { pid_t pid; pid = fork (); if (pid < 0){ printf("fork() error\n"); }else if (pid == 0){ printf("child process \n"); }else { printf("parent process \n"); } exit(0); } 进程创建流程 trace跟踪 用户程序调用glibc中的提供fork函数,fork函数触发系统调用clone, 去创建一个进程, 下面通过strace跟踪下编译链接后的可执行文件: # strace ./fork ... open("/lib64/libc.so.6", O_RDONLY|O_CLOEXEC) = 3 .... clone(child_stack=0, flags=CLONE_CHILD_CLEARTID|CLONE_CHILD_SETTID|SIGCHLD ,child_tidptr=0x7fb0be0eca10) = 16273 ... 从trace日志可以看到,在fork()对应系统调用clone而非fork fork man(2) Since version 2.3.3, rather than invoking the kernel’s fork() system call, the glibc fork() wrapper that is provided as part of the NPTL threading implementation invokes clone(2) with flags that provide the same effect as the traditional system call. (A call to fork() is equivalent to a call to clone(2) specifying flags as just SIGCHLD.) The glibc wrapper invokes any fork handlers that have been established using pthread_atfork(3). ...