考虑给出`fork`程序,下面的程序打印你好多少次?

时间:2016-08-25 13:20:44

标签: c process fork

  

请考虑下面给出的fork计划:

以下程序打印hello多少次?

main(int argc, char **argv) {
 int i;
 for (i=0; i < 3; i++) {
 fork();
 printf("hello\n”);
 }
}

总“你好”消息= 2 + 4 + 8 = 14(see question-1 at page-5)。

以下程序打印hello多少次?

#include <stdio.h>
#include <unistd.h>
main()
{
int i;
for (i=0; i<3; i++)
fork();
printf("hello\n");
}

总“你好”消息= 8(see question-4 at page-5)。

在我看来两个程序都是一样的。为什么解释/答案不同?

  你可以解释一下吗?

1 个答案:

答案 0 :(得分:0)

第一个程序中的printf("hello\n”);语句位于for循环内。

for (i=0; i < 3; i++) {
 fork();
 printf("hello\n”);
 }

并且,第二个程序中的printf("hello\n”);语句超出了for循环。

for (i=0; i<3; i++)
fork();//after semicolon printf is outside the for loop's block scope.
printf("hello\n");

这是给定代码之间的差异。

相关问题