fork系统调用fork()系统调用用于复制父进程从而创建一个新进程,称为子进程,它与进程(称为系统调用fork的进程)同时运行,此进程称为父进程。fork()的特殊之处在于:一次调用,两次返回。如果fork()执行出现了问题则会返回一个负数。如果fork()系统调用正常执行,会给父进程返回子进程的pid,给子进程返回0。
fork系统调用是通过do_fork来实现的,do_fork函数中进行了两个重要的操作,分别是拷贝父进程资源、子进程加入调度队列。do_fork函数首先会通过调用copy_process来将父进程所拥有的资源拷贝给子进程,并创建子进程。子进程创建成功后,会调用wake_up_new_task来将子进程加入就绪队列,等待CPU分配资源并运行。
代码如下
long _do_fork(struct kernel_clone_args *args) { u64 clone_flags = args->flags; struct completion vfork; struct pid *pid; struct task_struct *p; int trace = 0; long nr; /* * Determine whether and which event to report to ptracer. When * called from kernel_thread or CLONE_UNTRACED is explicitly * requested, no event is reported; otherwise, report if the event * for the type of forking is enabled. */ if (!(clone_flags & CLONE_UNTRACED)) { if (clone_flags & CLONE_VFORK) trace = PTRACE_EVENT_VFORK; else if (args->exit_signal != SIGCHLD) trace = PTRACE_EVENT_CLONE; else trace = PTRACE_EVENT_FORK; if (likely(!ptrace_event_enabled(current, trace))) trace = 0; } p = copy_process(NULL, trace, NUMA_NO_NODE, args); add_latent_entropy(); if (IS_ERR(p)) return PTR_ERR(p); /* * Do this prior waking up the new thread - the thread pointer * might get invalid after that point, if the thread exits quickly. */ trace_sched_process_fork(current, p); pid = get_task_pid(p, PIDTYPE_PID); nr = pid_vnr(pid); if (clone_flags & CLONE_PARENT_SETTID) put_user(nr, args->parent_tid); if (clone_flags & CLONE_VFORK) { p->vfork_done = &vfork; init_completion(&vfork); get_task_struct(p); } wake_up_new_task(p); /* forking complete and child started to run, tell ptracer */ if (unlikely(trace)) ptrace_event_pid(trace, pid); if (clone_flags & CLONE_VFORK) { if (!wait_for_vfork_done(p, &vfork)) ptrace_event_pid(PTRACE_EVENT_VFORK_DONE, pid); } put_pid(pid); return nr; }
当在用户态使用execve系统调用陷入到内核态时,execve在内核中会使用do_execve处理函数来加载可执行文件,并把用该可执行文件替换掉原来的可执行文件。当使用execve加载的可执行文件执行完毕后,会返回到用户态,此时的可执行文件已经不是原来被替换掉的旧的可执行文件了,而是新的可执行文件。
execve()系统调用的执行过程如下:
以正在运行的用户态进程X切换到用户态进程Y为例:
结合中断上下文切换和进程上下文切换分析Linux内核的一般执行过程
原文:https://www.cnblogs.com/H1K777/p/13132578.html