一段关于fork函数调用的代码,问最终屏幕上会打印出多少个“-”。
#include<unistd.h> #include<stdio.h> int main() { for(int i = 0; i < 2; ++i) { fork(); printf("-"); } printf("\n"); return 0; }
执行结果:
[root@Shentar ~/myprogs/c/forktest]# ./a.out -- -- -- --
分析:关于行缓冲的问题,printf方法将输出的内容写到stdout,标准输出默认是带行缓冲的,在没有遇到“\n”之前,输出内容一直在行缓冲内。fork会复制堆栈,包括行缓冲区内的内容。
上面的代码一共会起4个进程,在循环中,主进程会执行printf方法两次,另外3个进程中,有一个会执行2次,其他两个各执行1次,最终共执行6次,但由于行缓冲的原因,屏幕上面会打印出8个
修改一下程序代码,可以看得更清晰:
#include<unistd.h> #include<stdio.h> int main() { for(int i = 0; i < 2; ++i) { fork(); printf("-"); } printf("pid=%d\n", getpid()); sleep(100000); return 0; }
执行结果:
[root@Shentar ~/myprogs/c/forktest]# ./a.out --pid=3365 --pid=3366 --pid=3367 --pid=3364
进程id:
root 2672 0.0 0.1 4932 1580 pts/0 Ss 00:26 0:00 | \_ -bash root 3364 0.0 0.0 2864 724 pts/0 S+ 00:46 0:00 | \_ ./a.out root 3365 0.0 0.0 2864 300 pts/0 S+ 00:46 0:00 | \_ ./a.out root 3366 0.0 0.0 2864 280 pts/0 S+ 00:46 0:00 | | \_ ./a.out root 3367 0.0 0.0 2864 280 pts/0 S+ 00:46 0:00 | \_ ./a.out