微信扫描,分享到朋友圈和群
关于fork和行缓冲的问题
一段关于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
2 条评论
答案是唯一的,跟子进程是否先执行无关。第一个子进程会执行两遍printf函数。所以一定会输出两个“-”。
第一题的答案一定是这个?进程的执行顺序好像不是固定的吧,也许子进程比父进程更快执行,那么一开始就打印一个“-”