一个进程,包括代码、数据和分配给进程的资源。
fork的原意是:分裂。
fork()函数通过系统调用创建(分裂)一个与原来进程几乎完全相同的进程,也就是两个进程可以做完全相同的事,但如果初始参数或者传入的变量不同,两个进程也可以做不同的事。
一个进程调用fork()函数后,系统先给新的进程分配资源,例如存储数据和代码的空间。然后把原来的进程的所有值都复制到新的新进程中,只有少数值与原来的进程的值不同。
下面通过例子由浅入深学习fork()函数:
例一
程序代码:
int main()
{
pid_t pid;
语句 a;
pid = fork();
语句 b;
}
代码分析:
(1).当程序运行到 pid = fork()时,这个进程马上分裂(fork的中文意思)成两个进程,我们称为父进程和子进程
(2).fork的执行:fork函数被调用一次,但返回两次,两次返回的唯一区别是子进程的返回值是0,而父进程的返回值则是子进程的进程ID。(也可以理解为::fork函数被调用一次,但执行两次,父进程执行一次返回子进程的进程ID,子进程执行一次返回0) 子进程和父进程都执行在fork函数调用之后的代码即语句b,子进程是父进程的一个拷贝。例如,父进程的数据空间、堆栈空间都会给子进程一个拷贝,而不是共享这些内存。
例二
程序代码及注释:
#include <unistd.h>
#include <stdio.h>
#include <sys/types.h>//这个头文件不能少,否则pid_t没有定义
int main ()
{
pid_t fpid; //fpid表示fork函数返回的值,pid_t其实是一个typedef,也就是类型定义,真正的原型是unsigned int……
int count=0; //此时,只有一个进程在执行这段代码
fpid=fork(); //此时,有两个进程在执行这段代码
if (fpid < 0) //如果出现错误,fork返回一个负值;
printf("error in fork!");
else if (fpid == 0) //在子进程中,fork返回0;
{
printf("i am the child process, my process id is %d\n",getpid());
//getpid() 函数功能:取得进程识别码
printf("i am the child of my parent\n");
count++;
//printf("统计结果是: %d\n",count);
}
else //在父进程中,fork返回新创建子进程的进程ID。所以fpid=新建进程的ID
{
printf("i am the parent process, my process id is %d\n",getppid());
//还有一个记录父进程pid的变量,可以通过getppid()函数获得变量的值。
printf("i am the father of child\n");
count++;
//printf("统计结果是: %d\n",count);
}
printf("统计结果是: %d\n",count);
return 0;
}
运行结果是:
i am the parent process, my process id is 2375
i am the father of child
统计结果是: 1
i am the child process, my process id is 2447
i am the child of my parent
统计结果是: 1
代码分析:
前面为了好入门仅仅介绍根据fork()函数的返回值判断子进程还是父进程。在此,正式说明fork()函数一共有三种返回值:
a)在父进程中,fork返回新创建子进程的进程ID;
b)在子进程中,fork返回0;
c)如果出现错误,fork返回一个负值;
在fork函数执行完毕后,如果创建新进程成功,则出现两个进程,一个是子进程,一个是父进程。在子进程中,fork函数返回0,在父进程中,fork返回新创建子进程的进程ID。我们可以通过fork返回的值来判断当前进程是子进程还是父进程。至于fpid的值为什么在父子进程中不同。“其实就相当于链表,进程形成了链表,父进程的fpid(p 意味point)指向子进程的进程id, 因为子进程没有子进程,所以其fpid为0.
创建新进程成功后,系统中出现两个基本完全相同的进程,这两个进程执行没有固定的先后顺序,哪个进程先执行要看系统的进程调度策略。
两个进程的内容完全一样,打印的结果不一样那是因为判断条件的原因,上面列举的只是进程的代码和指令,还有变量哦。
在fork函数执行完毕后,如果创建新进程不成功fork出错可能有两种原因:
a)当前的进程数已经达到了系统规定的上限,这时errno的值被设置为EAGAIN。
b)系统内存不足,这时errno的值被设置为ENOMEM。
执行完fork后,进程1的变量为count=0,fpid!=0(父进程)。进程2的变量为count=0,fpid=0(子进程),这两个进程的变量都是独立的,存在不同的地址中,不是共用的,这就解释了为什么两次count++两次,打印结果却是1。
fork是把进程当前的情况拷贝一份,执行fork时,进程已经执行完了int count=0;fork只拷贝下一个要执行的代码到新的进程。
例三
程序代码:
#include <unistd.h>
#include <stdio.h>
int main(void)
{
int i=0;
//printf("i son/pa ppid pid fpid\n");
//ppid指当前进程的父进程的pid ,pid指当前进程的pid, fpid指fork返回给当前进程的值
for(i=0;i<2;i++)
{
pid_t fpid=fork();
if (fpid < 0) //如果出现错误,fork返回一个负值;
printf("error in fork!");
else if(fpid==0) //产生子进程
printf("%d child %4d %4d %4d\n",i,getppid(),getpid(),fpid);
else
printf("%d parent %4d %4d %4d\n",i,getppid(),getpid(),fpid);
}
return 0;
}
运行结果是:
0 parent 2043 3224 3225
0 child 3224 3225 0
1 parent 2043 3224 3226
1 parent 3224 3225 3227
1 child 1 3227 0
1 child 1 3226 0
这份代码比较有意思,我们来认真分析一下:
第一步:在父进程中,指令执行到for循环中,i=0,接着执行fork,fork执行完后,系统中出现两个进程,分别是p3224和p3225(后面我都用pxxxx表示进程id为xxxx的进程)。可以看到父进程p3224的父进程是p2043,子进程p3225的父进程正好是p3224。我们用一个链表来表示这个关系:
p2043->p3224->p3225
第一次fork后,p3224(父进程)的变量为i=0,fpid=3225(fork函数在父进程中返向子进程id),代码内容为:
for(i=0;i<2;i++){
pid_t fpid=fork();//执行完毕,i=0,fpid=3225
if(fpid==0)
printf("%d child %4d %4d %4d/n",i,getppid(),getpid(),fpid);
else
printf("%d parent %4d %4d %4d/n",i,getppid(),getpid(),fpid);
}
return 0;
p3225(子进程)的变量为i=0,fpid=0(fork函数在子进程中返回0),代码内容为:
for(i=0;i<2;i++){
pid_t fpid=fork();//执行完毕,i=0,fpid=0
if(fpid==0)
printf("%d child %4d %4d %4d\n",i,getppid(),getpid(),fpid);
else
printf("%d parent %4d %4d %4d\n",i,getppid(),getpid(),fpid);
}
return 0;
所以打印出结果:
0 parent 2043 3224 3225
0 child 3224 3225 0
第二步:假设父进程p3224先执行,当进入下一个循环时,i=1,接着执行fork,系统中又新增一个进程p3226,对于此时的父进程,p2043->p3224(当前进程)->p3226(被创建的子进程)。
对于子进程p3225,执行完第一次循环后,i=1,接着执行fork,系统中新增一个进程p3227,对于此进程,p3224->p3225(当前进程)->p3227(被创建的子进程)。从输出可以看到p3225原来是p3224的子进程,现在变成p3227的父进程。父子是相对的,这个大家应该容易理解。只要当前进程执行了fork,该进程就变成了父进程了,就打印出了parent。
所以打印出结果是:
1 parent 2043 3224 3226
1 parent 3224 3225 3227
第三步:第二步创建了两个进程p3226,p3227,这两个进程执行完printf函数后就结束了,因为这两个进程无法进入第三次循环,无法fork,该执行return 0;了,其他进程也是如此。
以下是p3226,p3227打印出的结果:
1 child 1 3227 0
1 child 1 3226 0
细心的读者可能注意到p3226,p3227的父进程难道不该是p3224和p3225吗,怎么会是1呢?这里得讲到进程的创建和死亡的过程,在p3224和p3225执行完第二个循环后,main函数就该退出了,也即进程该死亡了,因为它已经做完所有事情了。p3224和p3225死亡后,p3226,p3227就没有父进程了,这在操作系统是不被允许的,所以p3226,p3227的父进程就被置为1了,1是永远不会死亡的,这不仅跟机子的调度有关还跟进程的死亡有关。
进程的死亡:它可以是自然死亡,即运行到main函数的最后一个”}”,从容地离我们而去;也可以是自杀,自杀有2种方式,一种 是调用 exit函数,一种是在main函数内使用return,无论哪一种方式,它都可以留下遗书,放在返回值里保留下来;它还甚至能可被谋杀,被其它进程通过 另外一些方式结束他的生命。
例四
程序代码:
#include <unistd.h>
#include <stdio.h>
int main(void)
{
int i=0;
for(i=0;i<3;i++){
pid_t fpid=fork();
if(fpid==0)
printf("son\n");
else
printf("father\n");
}
return 0;
}
它的执行结果之一是:
father
son
father
father
father
father
son
son
father
son
son
son
father
son
之所以说结果之一,是因为,在实验的过程中,每次运行,结果都不一样。但father和son各出现七次是一定的。
代码分析:
for i=0 1 2
father father father
son
son father
son
son father father
son
son father
son
其中每一行分别代表一个进程的运行打印结果。
总结一下规律,对于这种N次循环的情况,执行printf函数的次数为2*(1+2+4+……+2N-1)次,创建的子进程数为1+2+4+……+2N-1个。(注释:此处的N-1是次方数)
同时,大家如果想测一下一个程序中到底创建了几个子进程,最好的方法就是调用printf函数打印该进程的pid,也即调用printf("%d/n",getpid());或者通过printf("+/n");来判断产生了几个进程。有人想通过调用printf("+");来统计创建了几个进程,这是不妥当的。具体原因我来分析,我们通过下面的例子来解释。
例五
程序代码:
#include <unistd.h>
#include <stdio.h>
int main() {
pid_t fpid;//fpid表示fork函数返回的值
//printf("fork!");
printf("fork!\n");
fpid = fork();
if (fpid < 0)
printf("error in fork!");
else if (fpid == 0)
printf("I am the child process, my process id is %d\n", getpid());
else
printf("I am the parent process, my process id is %d\n", getpid());
return 0;
}
执行结果如下:
fork!
I am the parent process, my process id is 3361
I am the child process, my process id is 3362
如果把语句printf("fork!\n");注释掉,执行printf("fork!");
则新的程序的执行结果是:
fork!I am the parent process, my process id is 3298
fork!I am the child process, my process id is 3299
程序解释:
程序的唯一的区别就在于一个\n回车符号,为什么结果会相差这么大呢?
这就跟printf的缓冲机制有关了,printf某些内容时,操作系统仅仅是把该内容放到了stdout的缓冲队列里了,并没有实际的写到屏幕上。但是,只要看到有\n 则会立即刷新stdout,因此就马上能够打印了。
运行了printf("fork!")后,“fork!”仅仅被放到了缓冲里,程序运行到fork时缓冲里面的“fork!” 被子进程复制过去了。因此在子进程度stdout缓冲里面就也有了fork! 。所以,你最终看到的会是fork! 被printf了2次!!!!
而运行printf("fork! \n")后,“fork!”被立即打印到了屏幕上,之后fork到的子进程里的stdout缓冲里不会有fork! 内容。因此你看到的结果会是fork! 被printf了1次!!!!
所以说printf("+");不能正确地反应进程的数量。
例六
程序代码:
#include <stdio.h>
#include <unistd.h>
int main(int argc, char* argv[])
{
fork();
fork() && fork() || fork(); //逻辑运算的优先级为非、与、或
fork();
return 0;
}
问题是不算main这个进程自身,程序到底创建了多少个进程。
为了解答这个问题,我们先做一下弊,先用程序验证一下,到此有多少个进程。
#include <stdio.h>
int main(int argc, char* argv[])
{
fork();
fork() && fork() || fork();
fork();
printf("+/n");
}
答案是总共20个进程,除去main进程,还有19个进程。
代码分析:
我们再来仔细分析一下,为什么是还有19个进程。
第一个fork和最后一个fork肯定是会执行的。
主要在中间3个fork上,可以画一个图进行描述。
这里就需要注意&&和||运算符。
A&&B,如果A=0,就没有必要继续执行&&B了;A非0,就需要继续执行&&B。
A||B,如果A非0,就没有必要继续执行||B了,A=0,就需要继续执行||B。
例七
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
int main()
{
pid_t pid;
int count=0;
pid = fork();
printf( "This is first time, pid = %d\n", pid );
printf( "This is second time, pid = %d\n", pid );
count++;
printf( "count = %d\n", count );
if ( pid>0 )
printf("This is the parent process,the child has the pid:%d\n",pid);
else if ( !pid )
printf("This is the child Process.\n");
else
printf("fork failed.\n");
printf("This is third time, pid = %d\n",pid);
printf("This is fouth time, pid = %d\n",pid);
return 0;
}
运行结果如下:
This is first time, pid = 2514
This is second time, pid = 2514
count = 1
This is the parent process,the child has the pid:2514
This is third time, pid = 2514
This is fouth time, pid = 2514
This is first time, pid = 0
This is second time, pid = 0
count = 1
This is the child Process.
This is third time, pid = 0
This is fouth time, pid = 0
例八
#include <unistd.h>
#include <stdio.h>
int main()
{
pid_t pid;
int count=0;
pid=fork();
printf("Now,the pid returned by calling fork() is %d\n",pid);
if(pid>0)
{
printf("This is the parent process,the child has the pid :%d\n",pid);
printf("In the parent process,count =%d\n",count);
}
else if(!pid)
{
printf("This is the child process.\n");
printf("Do your own things here.\n");
count ++;
printf("In the child process,count =%d\n",count);
}
else
printf("fork failed.\n");
return 0;
}
运行结果如下:
Now,the pid returned by calling fork() is 2883
This is the parent process,the child has the pid :2883
In the parent process,count =0
Now,the pid returned by calling fork() is 0
This is the child process.
Do your own things here.
In the child process,count =1
linux源代码-fork.c源代码
/* linux/kernel/fork.c //--fork()用于创建子进程*/
/* '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;
}