一个有趣的题目—linux中的fork函数分析

来源:互联网 发布:配电箱尺寸计算软件 编辑:程序博客网 时间:2024/06/05 02:17

首先要介绍一下printf的缓冲机制:printf输出内容时,并不是直接打印到屏幕上,而是先把内容放入到stdout的缓冲队列中。遇到\n或者刷新缓冲等情况时才会输出内容。

看一个小例子:

#include<stdio.h>#include<sys/types.h>#include<unistd.h>int main(){printf("hhhh");//printf("hhhh\n");int pid=fork();if(pid==0){printf("I am parent process!\n");}else if(pid>0){printf("I am child process!\n");}else{printf("Errof!\n");}return 0;}

fork()创建新进程时,会复制旧进程的一切内容,包括缓冲区的内容。因此,如果是printf("hhhh"),hhhh放入到缓冲区中,新进程缓冲区中也会有,结果新旧进程都会输出一次hhhh。而如果是printf("hhhh\n"),直接输出了,不存在于缓冲区中,新进程就不会输出hhhh。

 

下面看一个经常出现的笔试题目:

#include<stdio.h>#include<sys/types.h>#include<unistd.h>int main(){int i=0;for(i=0;i<2;i++){fork();printf("-\n");}}

会输出几个-?

 

#include<stdio.h>#include<sys/types.h>#include<unistd.h>int main(){int i=0;for(i=0;i<2;i++){fork();printf("-");}}

会输出几个-?

 

前一个输出6个,后一个输出8个。因为缓冲区的内容也被子进程复制了。

原创粉丝点击