前几天做实验,搞懂了fork函数的用法,写一篇笔记...
首先要知道fork()函数是一个 单调用双返回的函数,记得以前C语言的老师说过,函数只能有一个返回值,如果想有多个返回值,则必须用数组,或者指针,但在这里,fork()为什么有这么多的返回我不得而知..书上也只有写他是采用的copy_on_write机制实现的.
fork()的返回值有
大于0:当返回大于0的数时,他返回的应该是子进程的进程号.
等于0:表示,已创建子进程.
-1 : 创建子进程失败.
现在举例:
#include <stdio.h>
main()
{
int pid1;
if(pid1=fork()) { /*创建一个子进程暂时叫他child1,返回大于0的值,也就是进程号给pid1,返回 <=0的值给else,并同时执行 if语句和else 语句....在我们实验室里的机器上运行,总是会先运行子进程,也就是说,先运行else语句,可能是与linux的内核有关...*/
if(fork()) { //创建第二个子进程叫child2
printf("parent's context./n"); // 父进程主体.
printf("parent is waiting the child1 terminate./n");
wait(0); //等待第一个醒来的子进程
printf("parent is waiting the child2 terminate./n");
wait(0); //等待第二个醒来的子进程
printf("parent terminates./n");
exit(0); //退出
}
else { //child2 第二个子进程
printf("child2's context./n");
sleep(5); //休眠5S
printf("child2 terminate./n");
exit(0);
}
else if(pid1==0) { //child1 与第一个if 对应.
printf("child1's context./n");
sleep(10); //睡眠
printf("child1 terminate./n");
exit(0); //退出进程child1
}
}
在学校机房运行的结果是
child1's context. // 先运行第一个if 创建的子进程child1
child2's context. //child1等待10S,主进程继续执行,并运行第二个if 创建的child2
parent's context. //child2等待5S,主进程继续执行,并输出.
parent is waiting the child1 terminate.
child2 terminate. //由于child2等待了5S所以先备wait到.输出child2余下信息,并退出
parent is waiting the child2 terminate.
child1 terminate. //同上
parent terminates. //回到主进程,并结束...
有空的时候 ,我还会在自己的机上试一下.总觉得上面的结果有点不妥....
请高手指导.............
首先要知道fork()函数是一个 单调用双返回的函数,记得以前C语言的老师说过,函数只能有一个返回值,如果想有多个返回值,则必须用数组,或者指针,但在这里,fork()为什么有这么多的返回我不得而知..书上也只有写他是采用的copy_on_write机制实现的.
fork()的返回值有
大于0:当返回大于0的数时,他返回的应该是子进程的进程号.
等于0:表示,已创建子进程.
-1 : 创建子进程失败.
现在举例:
#include <stdio.h>
main()
{
int pid1;
if(pid1=fork()) { /*创建一个子进程暂时叫他child1,返回大于0的值,也就是进程号给pid1,返回 <=0的值给else,并同时执行 if语句和else 语句....在我们实验室里的机器上运行,总是会先运行子进程,也就是说,先运行else语句,可能是与linux的内核有关...*/
if(fork()) { //创建第二个子进程叫child2
printf("parent's context./n"); // 父进程主体.
printf("parent is waiting the child1 terminate./n");
wait(0); //等待第一个醒来的子进程
printf("parent is waiting the child2 terminate./n");
wait(0); //等待第二个醒来的子进程
printf("parent terminates./n");
exit(0); //退出
}
else { //child2 第二个子进程
printf("child2's context./n");
sleep(5); //休眠5S
printf("child2 terminate./n");
exit(0);
}
else if(pid1==0) { //child1 与第一个if 对应.
printf("child1's context./n");
sleep(10); //睡眠
printf("child1 terminate./n");
exit(0); //退出进程child1
}
}
在学校机房运行的结果是
child1's context. // 先运行第一个if 创建的子进程child1
child2's context. //child1等待10S,主进程继续执行,并运行第二个if 创建的child2
parent's context. //child2等待5S,主进程继续执行,并输出.
parent is waiting the child1 terminate.
child2 terminate. //由于child2等待了5S所以先备wait到.输出child2余下信息,并退出
parent is waiting the child2 terminate.
child1 terminate. //同上
parent terminates. //回到主进程,并结束...
有空的时候 ,我还会在自己的机上试一下.总觉得上面的结果有点不妥....
请高手指导.............