并发进程的不同输出结果

 

 

深入理解计算系统,499页有这么一个例题。这个例题的输出会产生多少行?可能顺序是什么?

 1 #include <stdio.h>
  2 #include <sys/types.h>
  3 #include <unistd.h>
  4 #include<sys/wait.h>
  5
  6 int main(){
  7   int status;
  8   pid_t pid;
  9   printf("hello\n");
 10   pid=fork();
 11   printf("%d\n",!pid);
 12   if(pid!=0){
 13     if(waitpid(-1,&status,0)>0){
 14       if(WIFEXITED(status)!=0)
 15         printf("%d\n",WEXITSTATUS(status));
 16     }
 17   }
 18   printf("bye\n");
 19   exit(2);
 20 }

一个可行的输出结果可能是这样的:

hello
0
1
bye
2
bye

其中 2,bye是最后要输出的。因为父进程要等待子进程的结束。Hello 是第一次要输出的。

 

现在我们讨论的焦点是,printf("hello\n")会不会被子进程copy ?

在第9行中,去掉“\n" ,结果如下:

hello0
hello1
bye
2
bye

这是因为不加 "\n"时,”hello"在缓冲区中,未输出。子进程会copy父进程中的缓冲区。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值