日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問(wèn) 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) > 运维知识 > linux >内容正文

linux

linux内核设计与实现---进程管理

發(fā)布時(shí)間:2023/12/1 linux 42 豆豆
生活随笔 收集整理的這篇文章主要介紹了 linux内核设计与实现---进程管理 小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

進(jìn)程管理

  • 1 進(jìn)程描述符及任務(wù)結(jié)構(gòu)
    • 分配進(jìn)程描述符
    • 進(jìn)程描述符的存放
    • 進(jìn)程狀態(tài)
    • 設(shè)置當(dāng)前進(jìn)程狀態(tài)
    • 進(jìn)程上下文
    • 進(jìn)程家族樹(shù)
  • 2 進(jìn)程創(chuàng)建
    • 寫時(shí)拷貝
    • fork()
    • vfork()
  • 3 線程在Linux中的實(shí)現(xiàn)
      • 內(nèi)核線程
  • 4 進(jìn)程終結(jié)
    • 刪除進(jìn)程描述符
    • 孤兒進(jìn)程造成的進(jìn)退微谷
  • 5 小結(jié)

進(jìn)程的另一個(gè)名字叫做任務(wù)(task)。Linux內(nèi)核通常把進(jìn)程也叫做任務(wù)。下面我們會(huì)交替使用任務(wù)和進(jìn)程兩個(gè)術(shù)語(yǔ)。

1 進(jìn)程描述符及任務(wù)結(jié)構(gòu)

內(nèi)核把進(jìn)程存放在叫作任務(wù)隊(duì)列(task list)的雙向循環(huán)鏈表中。鏈表中的每一項(xiàng)都是類型為task_struct、稱為進(jìn)程描述符的結(jié)構(gòu),該結(jié)構(gòu)定義在include/linux/sched.h文件中。進(jìn)程描述符包含一個(gè)具體進(jìn)程的所有信息。

struct task_struct {volatile long state; /* -1 unrunnable, 0 runnable, >0 stopped */struct thread_info *thread_info;atomic_t usage;unsigned long flags; /* per process flags, defined below */unsigned long ptrace;int lock_depth; /* Lock depth */int prio, static_prio;struct list_head run_list;prio_array_t *array;unsigned long sleep_avg;long interactive_credit;unsigned long long timestamp, last_ran;int activated;unsigned long policy;cpumask_t cpus_allowed;unsigned int time_slice, first_time_slice;#ifdef CONFIG_SCHEDSTATSstruct sched_info sched_info; #endifstruct list_head tasks;/** ptrace_list/ptrace_children forms the list of my children* that were stolen by a ptracer.*/struct list_head ptrace_children;struct list_head ptrace_list;struct mm_struct *mm, *active_mm;/* task state */struct linux_binfmt *binfmt;long exit_state;int exit_code, exit_signal;int pdeath_signal; /* The signal sent when the parent dies *//* ??? */unsigned long personality;unsigned did_exec:1;pid_t pid;pid_t tgid;/* * pointers to (original) parent process, youngest child, younger sibling,* older sibling, respectively. (p->father can be replaced with * p->parent->pid)*/struct task_struct *real_parent; /* real parent process (when being debugged) */struct task_struct *parent; /* parent process *//** children/sibling forms the list of my children plus the* tasks I'm ptracing.*/struct list_head children; /* list of my children */struct list_head sibling; /* linkage in my parent's children list */struct task_struct *group_leader; /* threadgroup leader *//* PID/PID hash table linkage. */struct pid pids[PIDTYPE_MAX];wait_queue_head_t wait_chldexit; /* for wait4() */struct completion *vfork_done; /* for vfork() */int __user *set_child_tid; /* CLONE_CHILD_SETTID */int __user *clear_child_tid; /* CLONE_CHILD_CLEARTID */unsigned long rt_priority;unsigned long it_real_value, it_prof_value, it_virt_value;unsigned long it_real_incr, it_prof_incr, it_virt_incr;struct timer_list real_timer;unsigned long utime, stime;unsigned long nvcsw, nivcsw; /* context switch counts */struct timespec start_time; /* mm fault and swap info: this can arguably be seen as either mm-specific or thread-specific */unsigned long min_flt, maj_flt; /* process credentials */uid_t uid,euid,suid,fsuid;gid_t gid,egid,sgid,fsgid;struct group_info *group_info;kernel_cap_t cap_effective, cap_inheritable, cap_permitted;unsigned keep_capabilities:1;struct user_struct *user; #ifdef CONFIG_KEYSstruct key *session_keyring; /* keyring inherited over fork */struct key *process_keyring; /* keyring private to this process (CLONE_THREAD) */struct key *thread_keyring; /* keyring private to this thread */ #endifunsigned short used_math;char comm[16]; /* file system info */int link_count, total_link_count; /* ipc stuff */struct sysv_sem sysvsem; /* CPU-specific state of this task */struct thread_struct thread; /* filesystem information */struct fs_struct *fs; /* open file information */struct files_struct *files; /* namespace */struct namespace *namespace; /* signal handlers */struct signal_struct *signal;struct sighand_struct *sighand;sigset_t blocked, real_blocked;struct sigpending pending;unsigned long sas_ss_sp;size_t sas_ss_size;int (*notifier)(void *priv);void *notifier_data;sigset_t *notifier_mask;void *security;struct audit_context *audit_context;/* Thread group tracking */u32 parent_exec_id;u32 self_exec_id; /* Protection of (de-)allocation: mm, files, fs, tty, keyrings */spinlock_t alloc_lock; /* Protection of proc_dentry: nesting proc_lock, dcache_lock, write_lock_irq(&tasklist_lock); */spinlock_t proc_lock; /* context-switch lock */spinlock_t switch_lock;/* journalling filesystem info */void *journal_info;/* VM state */struct reclaim_state *reclaim_state;struct dentry *proc_dentry;struct backing_dev_info *backing_dev_info;struct io_context *io_context;unsigned long ptrace_message;siginfo_t *last_siginfo; /* For ptrace use. */ /** current io wait handle: wait queue entry to use for io waits* If this thread is processing aio, this points at the waitqueue* inside the currently handled kiocb. It may be NULL (i.e. default* to a stack based synchronous wait) if its doing sync IO.*/wait_queue_t *io_wait; #ifdef CONFIG_NUMAstruct mempolicy *mempolicy;short il_next; /* could be shared with used_math */ #endif };

分配進(jìn)程描述符

Linux通過(guò)slab分配器分配task_struct結(jié)構(gòu),這樣能達(dá)到對(duì)象復(fù)用和緩存著色的目的(通過(guò)預(yù)先分配和重復(fù)使用task_struct,可以避免動(dòng)態(tài)分配和釋放所帶來(lái)的資源消耗)。在2.6以前的內(nèi)核中,各個(gè)進(jìn)程的task_struct存放在它們內(nèi)核棧的尾端。這樣做是為了讓那些x86這樣寄存器較少的硬件體系結(jié)構(gòu)只要通過(guò)棧指針就能計(jì)算出它的位置。由于現(xiàn)在用slab分配器動(dòng)態(tài)生成task_struct,所以只需在棧底(對(duì)于向下增長(zhǎng)的棧來(lái)說(shuō))或棧頂(對(duì)于向上增長(zhǎng)的的棧來(lái)說(shuō))創(chuàng)建一個(gè)新的結(jié)構(gòu)struct thread_info,thread_info有一個(gè)指向進(jìn)程描述符的指針。

在x86_64上,thread_info結(jié)構(gòu)在文件include/asm-x86_64/thread_info.h中

struct thread_info {struct task_struct *task; /* main task structure */struct exec_domain *exec_domain; /* execution domain */__u32 flags; /* low level flags */__u32 status; /* thread synchronous flags */__u32 cpu; /* current CPU */int preempt_count;mm_segment_t addr_limit; struct restart_block restart_block; };

每個(gè)任務(wù)的thread_info結(jié)構(gòu)在它的內(nèi)核棧的尾部分配。結(jié)構(gòu)中task域存放的是指向該任務(wù)實(shí)際task_struct的指針。每個(gè)進(jìn)程都有一個(gè)thread_info結(jié)構(gòu),指向自己的task_struct進(jìn)程描述符。

進(jìn)程描述符的存放

內(nèi)核通過(guò)一個(gè)唯一的進(jìn)程標(biāo)識(shí)值或PID來(lái)標(biāo)識(shí)每個(gè)進(jìn)程。PID是pid_t類型,是一個(gè)int類型。為了與老版本的Unix和Linux兼容,PID的最大值默認(rèn)設(shè)置為32768,內(nèi)核把每個(gè)進(jìn)程的PID存放在它們各自的進(jìn)程描述符中。
這個(gè)最大值很重要,因?yàn)樗鼘?shí)際上就是系統(tǒng)中允許同時(shí)存在的進(jìn)程的最大數(shù)目。如果確實(shí)需要的話,由系統(tǒng)管理員通過(guò)修改/proc/sys/kernel/pid_max來(lái)提高上線。
在內(nèi)核中,訪問(wèn)任務(wù)通常需要獲得指向其task_struct指針。可以通過(guò)current宏查找到當(dāng)前正在運(yùn)行進(jìn)程的進(jìn)程描述符。有的硬件體系結(jié)構(gòu)可以拿出一個(gè)專門寄存器來(lái)存放當(dāng)前進(jìn)程task_struct的地址。
在x86系統(tǒng)上,current宏定義在include/asm-m32r/current.h文件中。current把棧指針的后13個(gè)有效數(shù)字位屏蔽掉,用來(lái)計(jì)算出thread_info的偏移,因?yàn)閠hread_info結(jié)構(gòu)存放在它的內(nèi)核棧的尾端

static __inline__ struct task_struct *get_current(void) {return current_thread_info()->task; }#define current (get_current())static inline struct thread_info *current_thread_info(void) {struct thread_info *ti;__asm__ __volatile__ ("ldi %0, #0xffffe000; \n\t""and %0, sp; \n\t": "=r" (ti));return ti; }

這里內(nèi)核棧的大小是8KB,兩頁(yè),13位可以標(biāo)識(shí)8kb內(nèi)存地址,屏蔽13位剛剛好指向棧的尾端。

進(jìn)程狀態(tài)

進(jìn)程描述符中的state域描述了進(jìn)程的當(dāng)前狀態(tài)

volatile long state; /* -1 unrunnable, 0 runnable, >0 stopped */

系統(tǒng)中的每個(gè)進(jìn)程都必然處于五種進(jìn)程狀態(tài)中的一種。該域的值也必然為下列五種狀態(tài)標(biāo)志之一:

  • TASK_RUNNING(運(yùn)行):進(jìn)程是可執(zhí)行的;它或者正在執(zhí)行,或者在運(yùn)行隊(duì)列中等待執(zhí)行
  • TASK_INTERRUPTIBLE(可中斷):進(jìn)程正在睡眠(也就是被阻塞),等待某些條件的達(dá)成。一旦這些條件達(dá)成,內(nèi)核就會(huì)把進(jìn)程狀態(tài)設(shè)置為運(yùn)行。
  • TASK_UNINTERRUPTIBLE(不可中斷):除了不會(huì)因?yàn)榻邮艿叫盘?hào)而被喚醒從而投入運(yùn)行外,這個(gè)狀態(tài)與可打斷狀態(tài)相同。
  • TASK_ZOMBIE(僵死):該進(jìn)程已經(jīng)結(jié)束了,但是符父進(jìn)程還沒(méi)有調(diào)用wait4()系統(tǒng)調(diào)用,釋放相關(guān)資源。
  • TASK_STOPPED(停止):進(jìn)程停止運(yùn)行。

設(shè)置當(dāng)前進(jìn)程狀態(tài)

內(nèi)核經(jīng)常需要調(diào)整某個(gè)進(jìn)程的狀態(tài)。這時(shí)最好使用set_task_state函數(shù):

set_task_state(task,state)//將任務(wù)task的狀態(tài)設(shè)置為state #define set_task_state(tsk, state_value) \set_mb((tsk)->state, (state_value))

該函數(shù)將指定的進(jìn)程設(shè)置為指定的狀態(tài)。位置在/include/linux/sched.h文件中。
方法set_current_state(state)和set_task_state(current, state)含義是相同的。

進(jìn)程上下文

一般程序在用戶空間執(zhí)行。當(dāng)一個(gè)程序執(zhí)行了系統(tǒng)調(diào)用或者觸發(fā)了某個(gè)異常,它就陷入了內(nèi)核空間。此時(shí),我們稱內(nèi)核"代表進(jìn)程執(zhí)行"并處于進(jìn)程上下文中。在此上下文中的current宏是有效的。除非在此間隙有更高優(yōu)先級(jí)的進(jìn)程需要執(zhí)行并由調(diào)度器作出了相應(yīng)調(diào)整,否則在內(nèi)核退出的時(shí)候,程序恢復(fù)在用戶空間繼續(xù)執(zhí)行。

進(jìn)程家族樹(shù)

Unix系統(tǒng)的進(jìn)程之間存在明顯的繼承關(guān)系,在Linux系統(tǒng)中也是如此。所有的進(jìn)程都是PID為1的init進(jìn)程的后代。系統(tǒng)中的每個(gè)進(jìn)程必有一個(gè)父進(jìn)程。相應(yīng)的,每個(gè)進(jìn)程也可以擁有零個(gè)或多個(gè)子進(jìn)程。進(jìn)程間的關(guān)系存放在進(jìn)程描述符中。每個(gè)task_struct都包含一個(gè)指向其父進(jìn)程進(jìn)程描述符的parent指向,還包含一個(gè)稱為children的子進(jìn)程鏈表。所以對(duì)于當(dāng)前進(jìn)程,可以通過(guò)下面的代碼獲得其父進(jìn)程的進(jìn)程描述符:

struct task_struct *my_parent = current->parent; //current是指向當(dāng)前進(jìn)程的進(jìn)程描述符指針

同樣,也可以按以下方式依次訪問(wèn)子進(jìn)程

struct task_struct *task; struct list_head *list; list_for_each(list,&current->children){task = list_entry(list,struct task_struct,sibling);/* task現(xiàn)在指向當(dāng)前的某個(gè)子進(jìn)程 */ }

2 進(jìn)程創(chuàng)建

Unix的進(jìn)程創(chuàng)建很特別。許多其他的操作系統(tǒng)都提供了產(chǎn)生進(jìn)程的機(jī)制,首先在新的地址空間里創(chuàng)建進(jìn)程,讀入可執(zhí)行文件,最后開(kāi)始執(zhí)行。Unix把上述步驟分解到兩個(gè)單獨(dú)的函數(shù)中去執(zhí)行:fork()和exec()。首先,fork()通過(guò)拷貝當(dāng)前進(jìn)程創(chuàng)建一個(gè)子進(jìn)程。然后exec()函數(shù)負(fù)責(zé)讀取可執(zhí)行文件并將其載入地址空間開(kāi)始執(zhí)行。

寫時(shí)拷貝

Linux的fork()使用寫時(shí)拷貝(copy-on-write)頁(yè)實(shí)現(xiàn)。寫時(shí)拷貝是一種可以推遲甚至免除拷貝數(shù)據(jù)的技術(shù)。當(dāng)調(diào)用fork時(shí),內(nèi)核此時(shí)并不復(fù)制整個(gè)進(jìn)程地址空間,而是讓父進(jìn)程和子進(jìn)程共享同一個(gè)拷貝。只有在需要寫入的時(shí)候,數(shù)據(jù)才會(huì)被復(fù)制,從而使各個(gè)進(jìn)程擁有各自的拷貝。也就是說(shuō),資源的復(fù)制只有在需要寫入的時(shí)候才進(jìn)行,在此之前,只是以只讀方式共享。

fork()

Linux通過(guò)clone()系統(tǒng)調(diào)用實(shí)現(xiàn) fork()。這個(gè)調(diào)用通過(guò)一系列的參數(shù)標(biāo)志來(lái)指明父子進(jìn)程需要共享的資源。fork()、vfork()和__clone()庫(kù)函數(shù)都根據(jù)各自需要的參數(shù)標(biāo)志去調(diào)用clone()。然后由clone()去調(diào)用do_fork()。
do_fork()完成了創(chuàng)建中的大部分工作,它的定義在kernel/fork.c文件中。該函數(shù)調(diào)用copy_process函數(shù),然后讓進(jìn)程開(kāi)始運(yùn)行。copy_process函數(shù)完成的工作很有意思:

static task_t *copy_process(unsigned long clone_flags,unsigned long stack_start,struct pt_regs *regs,unsigned long stack_size,int __user *parent_tidptr,int __user *child_tidptr,int pid) {int retval;struct task_struct *p = NULL;if ((clone_flags & (CLONE_NEWNS|CLONE_FS)) == (CLONE_NEWNS|CLONE_FS))return ERR_PTR(-EINVAL);/** Thread groups must share signals as well, and detached threads* can only be started up within the thread group.*/if ((clone_flags & CLONE_THREAD) && !(clone_flags & CLONE_SIGHAND))return ERR_PTR(-EINVAL);/** Shared signal handlers imply shared VM. By way of the above,* thread groups also imply shared VM. Blocking this case allows* for various simplifications in other code.*/if ((clone_flags & CLONE_SIGHAND) && !(clone_flags & CLONE_VM))return ERR_PTR(-EINVAL);retval = security_task_create(clone_flags);if (retval)goto fork_out;retval = -ENOMEM;p = dup_task_struct(current);if (!p)goto fork_out;retval = -EAGAIN;if (atomic_read(&p->user->processes) >=p->signal->rlim[RLIMIT_NPROC].rlim_cur) {if (!capable(CAP_SYS_ADMIN) && !capable(CAP_SYS_RESOURCE) &&p->user != &root_user)goto bad_fork_free;}atomic_inc(&p->user->__count);atomic_inc(&p->user->processes);get_group_info(p->group_info);/** If multiple threads are within copy_process(), then this check* triggers too late. This doesn't hurt, the check is only there* to stop root fork bombs.*/if (nr_threads >= max_threads)goto bad_fork_cleanup_count;if (!try_module_get(p->thread_info->exec_domain->module))goto bad_fork_cleanup_count;if (p->binfmt && !try_module_get(p->binfmt->module))goto bad_fork_cleanup_put_domain;p->did_exec = 0;copy_flags(clone_flags, p);p->pid = pid;retval = -EFAULT;if (clone_flags & CLONE_PARENT_SETTID)if (put_user(p->pid, parent_tidptr))goto bad_fork_cleanup;p->proc_dentry = NULL;INIT_LIST_HEAD(&p->children);INIT_LIST_HEAD(&p->sibling);init_waitqueue_head(&p->wait_chldexit);p->vfork_done = NULL;spin_lock_init(&p->alloc_lock);spin_lock_init(&p->proc_lock);clear_tsk_thread_flag(p, TIF_SIGPENDING);init_sigpending(&p->pending);p->it_real_value = p->it_virt_value = p->it_prof_value = 0;p->it_real_incr = p->it_virt_incr = p->it_prof_incr = 0;init_timer(&p->real_timer);p->real_timer.data = (unsigned long) p;p->utime = p->stime = 0;p->lock_depth = -1; /* -1 = no lock */do_posix_clock_monotonic_gettime(&p->start_time);p->security = NULL;p->io_context = NULL;p->io_wait = NULL;p->audit_context = NULL; #ifdef CONFIG_NUMAp->mempolicy = mpol_copy(p->mempolicy);if (IS_ERR(p->mempolicy)) {retval = PTR_ERR(p->mempolicy);p->mempolicy = NULL;goto bad_fork_cleanup;} #endifp->tgid = p->pid;if (clone_flags & CLONE_THREAD)p->tgid = current->tgid;if ((retval = security_task_alloc(p)))goto bad_fork_cleanup_policy;if ((retval = audit_alloc(p)))goto bad_fork_cleanup_security;/* copy all the process information */if ((retval = copy_semundo(clone_flags, p)))goto bad_fork_cleanup_audit;if ((retval = copy_files(clone_flags, p)))goto bad_fork_cleanup_semundo;if ((retval = copy_fs(clone_flags, p)))goto bad_fork_cleanup_files;if ((retval = copy_sighand(clone_flags, p)))goto bad_fork_cleanup_fs;if ((retval = copy_signal(clone_flags, p)))goto bad_fork_cleanup_sighand;if ((retval = copy_mm(clone_flags, p)))goto bad_fork_cleanup_signal;if ((retval = copy_keys(clone_flags, p)))goto bad_fork_cleanup_mm;if ((retval = copy_namespace(clone_flags, p)))goto bad_fork_cleanup_keys;retval = copy_thread(0, clone_flags, stack_start, stack_size, p, regs);if (retval)goto bad_fork_cleanup_namespace;p->set_child_tid = (clone_flags & CLONE_CHILD_SETTID) ? child_tidptr : NULL;/** Clear TID on mm_release()?*/p->clear_child_tid = (clone_flags & CLONE_CHILD_CLEARTID) ? child_tidptr: NULL;/** Syscall tracing should be turned off in the child regardless* of CLONE_PTRACE.*/clear_tsk_thread_flag(p, TIF_SYSCALL_TRACE);/* Our parent execution domain becomes current domainThese must match for thread signalling to apply */p->parent_exec_id = p->self_exec_id;/* ok, now we should be set up.. */p->exit_signal = (clone_flags & CLONE_THREAD) ? -1 : (clone_flags & CSIGNAL);p->pdeath_signal = 0;p->exit_state = 0;/* Perform scheduler related setup */sched_fork(p);/** Ok, make it visible to the rest of the system.* We dont wake it up yet.*/p->group_leader = p;INIT_LIST_HEAD(&p->ptrace_children);INIT_LIST_HEAD(&p->ptrace_list);/* Need tasklist lock for parent etc handling! */write_lock_irq(&tasklist_lock);/** The task hasn't been attached yet, so cpus_allowed mask cannot* have changed. The cpus_allowed mask of the parent may have* changed after it was copied first time, and it may then move to* another CPU - so we re-copy it here and set the child's CPU to* the parent's CPU. This avoids alot of nasty races.*/p->cpus_allowed = current->cpus_allowed;set_task_cpu(p, smp_processor_id());/** Check for pending SIGKILL! The new thread should not be allowed* to slip out of an OOM kill. (or normal SIGKILL.)*/if (sigismember(&current->pending.signal, SIGKILL)) {write_unlock_irq(&tasklist_lock);retval = -EINTR;goto bad_fork_cleanup_namespace;}/* CLONE_PARENT re-uses the old parent */if (clone_flags & (CLONE_PARENT|CLONE_THREAD))p->real_parent = current->real_parent;elsep->real_parent = current;p->parent = p->real_parent;if (clone_flags & CLONE_THREAD) {spin_lock(&current->sighand->siglock);/** Important: if an exit-all has been started then* do not create this new thread - the whole thread* group is supposed to exit anyway.*/if (current->signal->group_exit) {spin_unlock(&current->sighand->siglock);write_unlock_irq(&tasklist_lock);retval = -EAGAIN;goto bad_fork_cleanup_namespace;}p->group_leader = current->group_leader;if (current->signal->group_stop_count > 0) {/** There is an all-stop in progress for the group.* We ourselves will stop as soon as we check signals.* Make the new thread part of that group stop too.*/current->signal->group_stop_count++;set_tsk_thread_flag(p, TIF_SIGPENDING);}spin_unlock(&current->sighand->siglock);}SET_LINKS(p);if (unlikely(p->ptrace & PT_PTRACED))__ptrace_link(p, current->parent);attach_pid(p, PIDTYPE_PID, p->pid);attach_pid(p, PIDTYPE_TGID, p->tgid);if (thread_group_leader(p)) {attach_pid(p, PIDTYPE_PGID, process_group(p));attach_pid(p, PIDTYPE_SID, p->signal->session);if (p->pid)__get_cpu_var(process_counts)++;}nr_threads++;write_unlock_irq(&tasklist_lock);retval = 0;fork_out:if (retval)return ERR_PTR(retval);return p;bad_fork_cleanup_namespace:exit_namespace(p); bad_fork_cleanup_keys:exit_keys(p); bad_fork_cleanup_mm:if (p->mm)mmput(p->mm); bad_fork_cleanup_signal:exit_signal(p); bad_fork_cleanup_sighand:exit_sighand(p); bad_fork_cleanup_fs:exit_fs(p); /* blocking */ bad_fork_cleanup_files:exit_files(p); /* blocking */ bad_fork_cleanup_semundo:exit_sem(p); bad_fork_cleanup_audit:audit_free(p); bad_fork_cleanup_security:security_task_free(p); bad_fork_cleanup_policy: #ifdef CONFIG_NUMAmpol_free(p->mempolicy); #endif bad_fork_cleanup:if (p->binfmt)module_put(p->binfmt->module); bad_fork_cleanup_put_domain:module_put(p->thread_info->exec_domain->module); bad_fork_cleanup_count:put_group_info(p->group_info);atomic_dec(&p->user->processes);free_uid(p->user); bad_fork_free:free_task(p);goto fork_out; }
  • 調(diào)用dup_task_struct()為新進(jìn)程創(chuàng)建一個(gè)內(nèi)核棧、thread_info結(jié)構(gòu)和task_struct,這些值與當(dāng)前進(jìn)程的值相同。此時(shí),子進(jìn)程和父進(jìn)程的描述符是完全相同的。
  • 檢查新創(chuàng)建的這個(gè)子進(jìn)程后,當(dāng)前用戶所擁有的進(jìn)程數(shù)目沒(méi)有超過(guò)給他分配的資源的限制
  • 現(xiàn)在,子進(jìn)程著手使自己與父進(jìn)程區(qū)別開(kāi)來(lái)。進(jìn)程描述符內(nèi)的許多成員都要被清0或設(shè)為初始值。
  • 接下來(lái),子進(jìn)程的狀態(tài)被設(shè)置為TASK_UNINTERRUPTIBLE以保證它不會(huì)投入運(yùn)行
  • copy_process()調(diào)用copy_flags()以更新task_struct的flags成員。
  • 調(diào)用get_pid()為新進(jìn)程獲取一個(gè)有效的PID
  • 根據(jù)傳遞給clone的參數(shù)標(biāo)志,copy_process拷貝或共享打開(kāi)的文件、文件系統(tǒng)消息等。
  • 讓父進(jìn)程和子進(jìn)程平分剩余的時(shí)間片
  • 最后,copy_process做掃尾工作并放回一個(gè)指向子進(jìn)程的指針。
    再回到do_fork()函數(shù),如果copy_process()成功返回,新創(chuàng)建的子進(jìn)程被喚醒并讓其投入運(yùn)行。

vfork()

vfork系統(tǒng)調(diào)用和fork()的功能相同,除了不拷貝父進(jìn)程的頁(yè)表項(xiàng)。子進(jìn)程作為父進(jìn)程的一個(gè)單獨(dú)的線程在它的地址空間運(yùn)行,父進(jìn)程被阻塞,直到子進(jìn)程退出或執(zhí)行exec()。
vfork系統(tǒng)調(diào)用的實(shí)現(xiàn)是通過(guò)向clone系統(tǒng)調(diào)用傳遞一個(gè)特殊標(biāo)志進(jìn)行的。

  • 在調(diào)用copy_process()時(shí),task_struct的vfork_done成員被設(shè)置為NULL
  • 在執(zhí)行do_fork()時(shí),如果給定特別標(biāo)志,則vfork_done會(huì)指向一個(gè)特殊地址
  • 子進(jìn)程開(kāi)始執(zhí)行后,父進(jìn)程不是立馬恢復(fù)執(zhí)行,而是一直等待,直到子進(jìn)程通過(guò)vfork_done指針向它發(fā)送信號(hào)
  • 在調(diào)用mm_release()時(shí),該函數(shù)用于進(jìn)程退出內(nèi)存地址空間,并且檢查vfork_done是否為空,如果不為空,則會(huì)向父進(jìn)程發(fā)送信號(hào)。
  • 回到do_fork(),父進(jìn)程醒來(lái)并返回。

3 線程在Linux中的實(shí)現(xiàn)

Linux實(shí)現(xiàn)線程的機(jī)制非常獨(dú)特。從內(nèi)核角度來(lái)說(shuō),它并沒(méi)有線程這個(gè)概念。Linux把所有的線程都當(dāng)做進(jìn)程來(lái)實(shí)現(xiàn)。內(nèi)核并沒(méi)有準(zhǔn)備特別的調(diào)度算法或是定義特別的數(shù)據(jù)結(jié)構(gòu)來(lái)表示線程。相反,線程僅僅被視為一個(gè)與其他進(jìn)程共享某些資源的**進(jìn)程。**每個(gè)進(jìn)程都有唯一自己的task_struct。所以在內(nèi)核中,它看起來(lái)像一個(gè)普通的線程。
線程的創(chuàng)建和普通進(jìn)程的創(chuàng)建類似,只不過(guò)在調(diào)用clone的時(shí)候需要傳遞一些參數(shù)標(biāo)志來(lái)指明需要的共享資源:

clone(CLONE_VM | CLONE_FS | CLONE_FILES | CLONE_SIGHAND,0)

上面的代碼產(chǎn)生的結(jié)構(gòu)和調(diào)用fork差不多,只是父子進(jìn)程共享地址空間、文件系統(tǒng)資源、文件描述符和信號(hào)處理程序。
一個(gè)普通的fork實(shí)現(xiàn)是:

clone(CLONE_VFORK | CLONE_VM | CLONE_SIGHAND,0)

傳遞給clone的參數(shù)標(biāo)志決定了新創(chuàng)建進(jìn)程的行為方式和父子進(jìn)程之間共享的資源種類。這些參數(shù)標(biāo)志定義在include/linux/sched.h文件中。

/** cloning flags:*/ #define CSIGNAL 0x000000ff /* signal mask to be sent at exit */ #define CLONE_VM 0x00000100 /* set if VM shared between processes */ #define CLONE_FS 0x00000200 /* set if fs info shared between processes */ #define CLONE_FILES 0x00000400 /* set if open files shared between processes */ #define CLONE_SIGHAND 0x00000800 /* set if signal handlers and blocked signals shared */ #define CLONE_PTRACE 0x00002000 /* set if we want to let tracing continue on the child too */ #define CLONE_VFORK 0x00004000 /* set if the parent wants the child to wake it up on mm_release */ #define CLONE_PARENT 0x00008000 /* set if we want to have the same parent as the cloner */ #define CLONE_THREAD 0x00010000 /* Same thread group? */ #define CLONE_NEWNS 0x00020000 /* New namespace group? */ #define CLONE_SYSVSEM 0x00040000 /* share system V SEM_UNDO semantics */ #define CLONE_SETTLS 0x00080000 /* create a new TLS for the child */ #define CLONE_PARENT_SETTID 0x00100000 /* set the TID in the parent */ #define CLONE_CHILD_CLEARTID 0x00200000 /* clear the TID in the child */ #define CLONE_DETACHED 0x00400000 /* Unused, ignored */ #define CLONE_UNTRACED 0x00800000 /* set if the tracing process can't force CLONE_PTRACE on this clone */ #define CLONE_CHILD_SETTID 0x01000000 /* set the TID in the child */ #define CLONE_STOPPED 0x02000000 /* Start in stopped state */

內(nèi)核線程

內(nèi)核線程是獨(dú)立運(yùn)行在內(nèi)核空間的標(biāo)準(zhǔn)進(jìn)程,內(nèi)核線程和普通的進(jìn)程間的區(qū)別在于內(nèi)核線程沒(méi)有獨(dú)立的地址空間(mm指針被設(shè)置為NULL)。它們只在內(nèi)核空間運(yùn)行,從來(lái)不切換到用戶空間去。內(nèi)核進(jìn)程和普通進(jìn)程一樣,可以被調(diào)度,也可以被搶占。
內(nèi)核線程只能由其他內(nèi)核線程創(chuàng)建,在現(xiàn)有內(nèi)核線程創(chuàng)建一個(gè)新的內(nèi)核線程的方法如下:

int kernel_thread(int (*fn)(void*),void *arg,unsigned long flags);

新的任務(wù)也是通過(guò)向普通的clone()系統(tǒng)調(diào)用傳遞特定的flags參數(shù)而創(chuàng)建的。在上面的函數(shù)返回時(shí),父線程退出,并返回一個(gè)指向子線程task_struct的指針。

4 進(jìn)程終結(jié)

當(dāng)一個(gè)進(jìn)程終結(jié)時(shí),內(nèi)核必須釋放它所占有的資源并把這一消息傳給父進(jìn)程。不論進(jìn)程是怎樣終結(jié)的,該任務(wù)大部分都要靠do_exit()來(lái)完成,do_exit()定義在kernel/exit.c文件中

fastcall NORET_TYPE void do_exit(long code) {struct task_struct *tsk = current;int group_dead;profile_task_exit(tsk);if (unlikely(in_interrupt()))panic("Aiee, killing interrupt handler!");if (unlikely(!tsk->pid))panic("Attempted to kill the idle task!");if (unlikely(tsk->pid == 1))panic("Attempted to kill init!");if (tsk->io_context)exit_io_context();tsk->flags |= PF_EXITING;del_timer_sync(&tsk->real_timer);if (unlikely(in_atomic()))printk(KERN_INFO "note: %s[%d] exited with preempt_count %d\n",current->comm, current->pid,preempt_count());if (unlikely(current->ptrace & PT_TRACE_EXIT)) {current->ptrace_message = code;ptrace_notify((PTRACE_EVENT_EXIT << 8) | SIGTRAP);}group_dead = atomic_dec_and_test(&tsk->signal->live);if (group_dead)acct_process(code);__exit_mm(tsk);exit_sem(tsk);__exit_files(tsk);__exit_fs(tsk);exit_namespace(tsk);exit_thread();exit_keys(tsk);if (group_dead && tsk->signal->leader)disassociate_ctty(1);module_put(tsk->thread_info->exec_domain->module);if (tsk->binfmt)module_put(tsk->binfmt->module);tsk->exit_code = code;exit_notify(tsk); #ifdef CONFIG_NUMAmpol_free(tsk->mempolicy);tsk->mempolicy = NULL; #endifBUG_ON(!(current->flags & PF_DEAD));schedule();BUG();/* Avoid "noreturn function does return". */for (;;) ; }
  • 首先,將task_struct中的標(biāo)志成員設(shè)置為PF_EXITING
  • 其次,調(diào)用del_timer_sync()喊出任一內(nèi)核定時(shí)器
  • 如果BSD的進(jìn)程記賬功能是開(kāi)啟的,do_exit()調(diào)用acct_process()來(lái)輸出記賬信息。
  • 然后調(diào)用_exit_mm()函數(shù)放棄進(jìn)程占用的mm_struct,如果沒(méi)有別的進(jìn)程使用它們,就徹底釋放它們
  • 接下來(lái)調(diào)用exit_sem()函數(shù)。如果進(jìn)程排隊(duì)等候IPC信號(hào),則離開(kāi)隊(duì)列
  • 調(diào)用_exit_files()、_exit_fs()、_exit_namespce()和exit_sighand(),分別遞減文件描述符、文件系統(tǒng)數(shù)據(jù)、進(jìn)程名字空間和信號(hào)處理函數(shù)的引用計(jì)數(shù)。如果其中某些引用計(jì)數(shù)的值降為0,那么久代表沒(méi)有進(jìn)程在使用相應(yīng)的資源,此時(shí)可以釋放。
  • 接著把存放在task_struct的exit_code成員中的任務(wù)退出碼置為exit()提供的代碼中,或者去完成任何其他由內(nèi)核機(jī)制規(guī)定的退出動(dòng)作
  • 調(diào)用exit_notify()向父進(jìn)程發(fā)送信號(hào),將子進(jìn)程的父進(jìn)程重新設(shè)置為線程組中的其他線程或init進(jìn)程,并把進(jìn)程狀態(tài)設(shè)置為TASK_ZOMBLE
  • 最后,do_exit()調(diào)用schedule()切換到其他進(jìn)程。

至此,與進(jìn)程相關(guān)聯(lián)的所有資源都被釋放掉了,只是相關(guān)聯(lián)的資源被釋放了,進(jìn)程還有資源沒(méi)有被釋放,它剩下所占用的所有資源就是內(nèi)核棧、thread_info結(jié)構(gòu)和task_struct結(jié)構(gòu)。此時(shí)進(jìn)程存在的唯一目的就是向它的父進(jìn)程提供信息。父進(jìn)程檢索到信息后,或者通知內(nèi)核那是無(wú)關(guān)的信息后,由進(jìn)程所持有的剩余內(nèi)存被釋放,歸還給系統(tǒng)使用。

刪除進(jìn)程描述符

在調(diào)用do_exit()之后,盡管線程已經(jīng)僵死不能再運(yùn)行了,但是系統(tǒng)還保留了它的進(jìn)程描述符。這樣做可以讓系統(tǒng)有辦法在子進(jìn)程終結(jié)后仍能獲得它的信息。
當(dāng)最終需要釋放進(jìn)程描述符時(shí),release_task()會(huì)被調(diào)用,用于完成以下工作:

  • 首先,它調(diào)用free_uid()來(lái)減少該進(jìn)程擁有者的進(jìn)程使用計(jì)數(shù)。
  • 然后,release_task()調(diào)用unhash_process()從pidhash上刪除該進(jìn)程,同時(shí)也要從task_list中刪除該進(jìn)程
  • 接下來(lái),如果這個(gè)進(jìn)程正在被普通race跟蹤,release_task()將跟蹤進(jìn)程的父進(jìn)程重設(shè)為最初的父進(jìn)程并將它從ptrace list上刪除。
  • 最后,release_task()調(diào)用put_task_struct()釋放該進(jìn)程內(nèi)核棧和thread_info結(jié)構(gòu)所占的頁(yè),并釋放task_struct所占的深藍(lán)高速緩存、

至此,進(jìn)程描述符和所有進(jìn)程獨(dú)享的資源就全部釋放掉了。

孤兒進(jìn)程造成的進(jìn)退微谷

如果父進(jìn)程在子進(jìn)程之前退出,那么必須有機(jī)制來(lái)保證子進(jìn)程能找到一個(gè)新的父親,否則的話這些成為孤兒的進(jìn)程就會(huì)在退出時(shí)永遠(yuǎn)處于僵死狀態(tài),白白的耗費(fèi)內(nèi)存。解決方案:子進(jìn)程在當(dāng)前線程組(父進(jìn)程所在的線程組)內(nèi)找一個(gè)線程作為父親,如果不行,就讓init作為它們的父進(jìn)程。在do_exit()中會(huì)調(diào)用notify_parent(),該函數(shù)會(huì)通過(guò)forget_original_parent()來(lái)執(zhí)行尋父過(guò)程。

static inline void forget_original_parent(struct task_struct * father,struct list_head *to_release) {struct task_struct *p, *reaper = father;struct list_head *_p, *_n;do {reaper = next_thread(reaper);if (reaper == father) {reaper = child_reaper;break;}} while (reaper->exit_state >= EXIT_ZOMBIE);/** There are only two places where our children can be:** - in our child list* - in our ptraced child list** Search them and reparent children.*/list_for_each_safe(_p, _n, &father->children) {int ptrace;p = list_entry(_p,struct task_struct,sibling);ptrace = p->ptrace;/* if father isn't the real parent, then ptrace must be enabled */BUG_ON(father != p->real_parent && !ptrace);if (father == p->real_parent) {/* reparent with a reaper, real father it's us */choose_new_parent(p, reaper, child_reaper);reparent_thread(p, father, 0);} else {/* reparent ptraced task to its real parent */__ptrace_unlink (p);if (p->exit_state == EXIT_ZOMBIE && p->exit_signal != -1 &&thread_group_empty(p))do_notify_parent(p, p->exit_signal);}/** if the ptraced child is a zombie with exit_signal == -1* we must collect it before we exit, or it will remain* zombie forever since we prevented it from self-reap itself* while it was being traced by us, to be able to see it in wait4.*/if (unlikely(ptrace && p->exit_state == EXIT_ZOMBIE && p->exit_signal == -1))list_add(&p->ptrace_list, to_release);}list_for_each_safe(_p, _n, &father->ptrace_children) {p = list_entry(_p,struct task_struct,ptrace_list);choose_new_parent(p, reaper, child_reaper);reparent_thread(p, father, 1);} }

先在線程組里找一個(gè)線程作為父進(jìn)程,如果線程組內(nèi)沒(méi)有其他的進(jìn)程,就將init設(shè)為父進(jìn)程。當(dāng)合適的父進(jìn)程找到后,只需要遍歷所有子進(jìn)程并為它們?cè)O(shè)置新的父進(jìn)程。

后面遍歷了兩個(gè)鏈表:子進(jìn)程鏈表和ptrace子進(jìn)程鏈表。給每個(gè)子進(jìn)程設(shè)置新的父進(jìn)程。當(dāng)一個(gè)進(jìn)程被跟蹤時(shí),它被暫時(shí)設(shè)定為調(diào)試進(jìn)程的子進(jìn)程。此時(shí)如果它的父進(jìn)程退出了,系統(tǒng)會(huì)為它和它所有的兄弟重新找一個(gè)父進(jìn)程。在以前的內(nèi)核中,這就需要遍歷系統(tǒng)所有的進(jìn)程來(lái)找這些子進(jìn)程,現(xiàn)在的解決辦法是在一個(gè)單獨(dú)的ptrace跟蹤的子進(jìn)程鏈表中搜索相關(guān)的兄弟進(jìn)程,用兩個(gè)相關(guān)鏈表減輕了遍歷帶來(lái)的消耗。

5 小結(jié)

在本文中,我們討論進(jìn)程的一般特效,它為何如此重要,以及進(jìn)程與線程之間的關(guān)系。然后,討論了Linux如何存放和表示進(jìn)程(用task_struct和thread_info),如果創(chuàng)建進(jìn)程(通過(guò)clone()和fork()),如何把新的執(zhí)行映像裝入到地址空間(通過(guò)exec()調(diào)用族),如何表示進(jìn)程的層次關(guān)系,父進(jìn)程又是如何收集后代的信息(通過(guò)wait()系統(tǒng)調(diào)用族),以及進(jìn)程最終如何死亡(強(qiáng)制或自愿調(diào)用exit())。

總結(jié)

以上是生活随笔為你收集整理的linux内核设计与实现---进程管理的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。

如果覺(jué)得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。