Linux C編程--fork()詳解

在Linux系統下學習一個系統函數最好的方法就是閱讀其源碼,首先,給出fork函數的源碼

/*
*  linux/kernel/fork.c
*                                //--fork()用於創建子進程
*  (C) 1991  Linus Torvalds
*/
/*
*  'fork.c' contains the help-routines for the 'fork' system call
* (see also system_call.s), and some misc functions ('verify_area').
* Fork is rather simple, once you get the hang of it, but the memory
* management can be a bitch. See 'mm/mm.c': 'copy_page_tables()'
*/
#include <errno.h>
#include <linux/sched.h>
#include <linux/kernel.h>
#include <asm/segment.h>
#include <asm/system.h>
                                //--寫頁面驗證,若頁面不可寫,則複製頁面
extern void write_verify(unsigned long address);
long last_pid=0;
                                //--進程空間區域寫前驗證函數
void verify_area(void * addr,int size)
{
    unsigned long start;
    start = (unsigned long) addr;
    size += start & 0xfff;
    start &= 0xfffff000;
    start += get_base(current->ldt[2]);        //--邏輯地址到線性地址的轉換
    while (size>0) {
        size -= 4096;
        write_verify(start);
        start += 4096;
    }
}
int copy_mem(int nr,struct task_struct * p)        //--複製內存頁表
{                                                //--由於採用寫時複製技術,這裏只複製目錄和頁表項,不分配內存
    unsigned long old_data_base,new_data_base,data_limit;
    unsigned long old_code_base,new_code_base,code_limit;
    code_limit=get_limit(0x0f);                    //--取段限長
    data_limit=get_limit(0x17);
    old_code_base = get_base(current->ldt[1]);
    old_data_base = get_base(current->ldt[2]);
    if (old_data_base != old_code_base)
        panic("We don't support separate I&D");
    if (data_limit < code_limit)
        panic("Bad data_limit");
    new_data_base = new_code_base = nr * TASK_SIZE;
    p->start_code = new_code_base;
    set_base(p->ldt[1],new_code_base);
    set_base(p->ldt[2],new_data_base);
    if (copy_page_tables(old_data_base,new_data_base,data_limit)) {        //--複製頁表
        free_page_tables(new_data_base,data_limit);
        return -ENOMEM;
    }
    return 0;
}
/*
*  Ok, this is the main fork-routine. It copies the system process
* information (task[nr]) and sets up the necessary registers. It
* also copies the data segment in it's entirety.
*/                                    //--fork()子程序,它複製系統進程信息,設置寄存器,複製數據段(代碼段)
int copy_process(int nr,long ebp,long edi,long esi,long gs,long none,
        long ebx,long ecx,long edx, long orig_eax, 
        long fs,long es,long ds,
        long eip,long cs,long eflags,long esp,long ss)        //--複製進程
{
    struct task_struct *p;
    int i;
    struct file *f;
    p = (struct task_struct *) get_free_page();                //--爲新任務數據結構分配內存
    if (!p)
        return -EAGAIN;
    task[nr] = p;
    *p = *current;    /* NOTE! this doesn't copy the supervisor stack */
    p->state = TASK_UNINTERRUPTIBLE;
    p->pid = last_pid;
    p->counter = p->priority;
    p->signal = 0;
    p->alarm = 0;
    p->leader = 0;        /* process leadership doesn't inherit */
    p->utime = p->stime = 0;
    p->cutime = p->cstime = 0;
    p->start_time = jiffies;
    p->tss.back_link = 0;
    p->tss.esp0 = PAGE_SIZE + (long) p;
    p->tss.ss0 = 0x10;
    p->tss.eip = eip;
    p->tss.eflags = eflags;
    p->tss.eax = 0;
    p->tss.ecx = ecx;
    p->tss.edx = edx;
    p->tss.ebx = ebx;
    p->tss.esp = esp;
    p->tss.ebp = ebp;
    p->tss.esi = esi;
    p->tss.edi = edi;
    p->tss.es = es & 0xffff;
    p->tss.cs = cs & 0xffff;
    p->tss.ss = ss & 0xffff;
    p->tss.ds = ds & 0xffff;
    p->tss.fs = fs & 0xffff;
    p->tss.gs = gs & 0xffff;
    p->tss.ldt = _LDT(nr);
    p->tss.trace_bitmap = 0x80000000;
    if (last_task_used_math == current)
        __asm__("clts ; fnsave %0 ; frstor %0"::"m" (p->tss.i387));
    if (copy_mem(nr,p)) {
        task[nr] = NULL;
        free_page((long) p);
        return -EAGAIN;
    }
    for (i=0; i<NR_OPEN;i++)                    //--如果父進程中有文件是打開的,則將對應文件的打開次數增1
        if (f=p->filp[i])
            f->f_count++;
    if (current->pwd)
        current->pwd->i_count++;
    if (current->root)
        current->root->i_count++;
    if (current->executable)
        current->executable->i_count++;
    if (current->library)
        current->library->i_count++;
    set_tss_desc(gdt+(nr<<1)+FIRST_TSS_ENTRY,&(p->tss));    //--在GDT表中設置新任務的TSS和LDT
    set_ldt_desc(gdt+(nr<<1)+FIRST_LDT_ENTRY,&(p->ldt));
    p->p_pptr = current;
    p->p_cptr = 0;
    p->p_ysptr = 0;
    p->p_osptr = current->p_cptr;
    if (p->p_osptr)
        p->p_osptr->p_ysptr = p;
    current->p_cptr = p;
    p->state = TASK_RUNNING;    /* do this last, just in case */
    return last_pid;
}
int find_empty_process(void)                        //--爲新進程取得不重複的進程號last_pid
{
    int i;
    repeat:
        if ((++last_pid)<0) last_pid=1;
        for(i=0 ; i<NR_TASKS ; i++)
            if (task[i] && ((task[i]->pid == last_pid) ||
                        (task[i]->pgrp == last_pid)))
                goto repeat;
    for(i=1 ; i<NR_TASKS ; i++)
        if (!task[i])
            return i;
    return -EAGAIN;
}

以下給出說明:

 fork函數
#include <sys/types.h> 
#include <unistd.h>  pid_t fork(void);

fork調用失敗則返回-1,調用成功的返回值見下面的解釋。我們通過一個例子來理解fork是怎樣創建新進程的。

這個程序的運行過程如下圖所示。


  1. 父進程初始化。

  2. 父進程調用fork,這是一個系統調用,因此進入內核。

  3. 內核根據父進程複製出一個子進程,父進程和子進程的PCB信息相同,用戶態代碼和數據也相同。因此,子進程現在的狀態看起來和父進程一樣,做完了初始化,剛調用了fork進入內核,還沒有從內核返回

  4. 現在有兩個一模一樣的進程看起來都調用了fork進入內核等待從內核返回(實際上fork只調用了一次),此外系統中還有很多別的進程也等待從內核返回。是父進程先返回還是子進程先返回,還是這兩個進程都等待,先去調度執行別的進程,這都不一定,取決於內核的調度算法。

  5. 如果某個時刻父進程被調度執行了,從內核返回後就從fork函數返回,保存在變量pid中的返回值是子進程的id,是一個大於0的整數,因此執下面的else分支,然後執行for循環,打印"This is the parent\n"三次之後終止。

  6. 如果某個時刻子進程被調度執行了,從內核返回後就從fork函數返回,保存在變量pid中的返回值是0,因此執行下面的if (pid == 0)分支,然後執行for循環,打印"This is the child\n"六次之後終止。fork調用把父進程的數據複製一份給子進程,但此後二者互不影響,在這個例子中,fork調用之後父進程和子進程的變量messagen被賦予不同的值,互不影響。

  7. 父進程每打印一條消息就睡眠1秒,這時內核調度別的進程執行,在1秒這麼長的間隙裏(對於計算機來說1秒很長了)子進程很有可能被調度到。同樣地,子進程每打印一條消息就睡眠1秒,在這1秒期間父進程也很有可能被調度到。所以程序運行的結果基本上是父子進程交替打印,但這也不是一定的,取決於系統中其它進程的運行情況和內核的調度算法,如果系統中其它進程非常繁忙則有可能觀察到不同的結果。另外,讀者也可以把sleep(1);去掉看程序的運行結果如何。

  8. 這個程序是在Shell下運行的,因此Shell進程是父進程的父進程。父進程運行時Shell進程處於等待狀態,當父進程終止時Shell進程認爲命令執行結束了,於是打印Shell提示符,而事實上子進程這時還沒結束,所以子進程的消息打印到了Shell提示符後面。最後光標停在This is the child的下一行,這時用戶仍然可以敲命令,即使命令不是緊跟在提示符後面,Shell也能正確讀取。

fork函數的特點概括起來就是“調用一次,返回兩次”,在父進程中調用一次,在父進程和子進程中各返回一次。從上圖可以看出,一開始是一個控制流程,調用fork之後發生了分叉,變成兩個控制流程,這也就是“fork”(分叉)這個名字的由來了。子進程中fork的返回值是0,而父進程中fork的返回值則是子進程的id(從根本上說fork是從內核返回的,內核自有辦法讓父進程和子進程返回不同的值),這樣當fork函數返回後,程序員可以根據返回值的不同讓父進程和子進程執行不同的代碼。

fork的返回值這樣規定是有道理的。fork在子進程中返回0,子進程仍可以調用getpid函數得到自己的進程id,也可以調用getppid函數得到父進程的id。在父進程中用getpid可以得到自己的進程id,然而要想得到子進程的id,只有將fork的返回值記錄下來,別無它法。

fork的另一個特性是所有由父進程打開的描述符都被複制到子進程中。父、子進程中相同編號的文件描述符在內核中指向同一個file結構體,也就是說,file結構體的引用計數要增加。


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章