标题: linux fork()函数学习 [打印本页] 作者: iceway 时间: 2008-08-13 09:22 标题: linux fork()函数学习
在编写socket ftp之前,我们先学习fork函数
先看这段范例代码:
#include unistd.h>;
#include sys/types.h>;
main ()
{
pid_t pid;
pid=fork();
if (pid 0)
printf("error in fork!");
else if (pid == 0)
printf("i am the child process, my process id is %dn",getpid());
else
printf("i am the parent process, my process id is %dn",getpid());
}
这段代码写了一个使用fork函数创建子进程,父子进程同时运行而产生交错的,不一样的运行结果。
运行结果如下:
[root@localhost c]# ./a.out
i am the child process, my process id is 4286
i am the parent process, my process id is 4285
fork在英文中是叉子,分叉的意思,在函数fork中,取后面的意思。很形象的表示程序从这里分叉,fork函数创建了子进程,子进程和父进程同时(其实是cpu分时处理)开始运行分叉之后的程序。
我把程序改写了一下:
{
printf("father\n");
}
}
return 0;
}
大家想想看最后将出现几个son 几个father呢?
。
。
。
。
。
。
。
对一下答案吧:
[hardy@localhost fork]$ ./fork
father
son
son
son
father
father
son
father
son
son
father
father
son
father
总共7个son7个father。你答对了么?
这道题需要在纸上画画才好理解
for i=0 1 2
father father father
son
son father
son
son father father
son
son father
son
其中每一行分别代表一个进程的运行打印结果。
当产生子进程的时刻,子进程打印son,当子进程调用fork的生成子子进程,他就提升为father。
总结来说,father永远打印father,son在fork之前是son,fork之后就为father,同时生成新的son。
这个比喻就像真正的父子,孩子长大了生了小孩,孩子就成了父亲。而父亲永远是父亲。
可以参考 该页面
讲解非常详细,各楼回答很精彩.