Chinaunix首页 | 论坛 | 博客
  • 博客访问: 435298
  • 博文数量: 132
  • 博客积分: 2511
  • 博客等级: 大尉
  • 技术积分: 1385
  • 用 户 组: 普通用户
  • 注册时间: 2006-04-11 15:10
文章分类

全部博文(132)

文章存档

2012年(18)

2011年(35)

2010年(60)

2009年(19)

分类: LINUX

2011-05-22 10:08:38

  1. /*
  2.  * 这个例子印象最深的就是那句解释:如果stdout连接到终端设
  3.  * 备,则它是行缓冲的,否则是全缓冲的,5.12节也对此有说明。
  4.  * 这就是为什么程序执行时如果把输出重定向到文件,则会发现
  5.  * before fork被输出了两次,因为在fork之前,printf执行后,
  6.  * 它没有被flush,还在父进程的缓冲区中,子进程复制了父进程
  7.  * 的堆栈后,它也存在子进程的缓冲区,最后跟后面那条printf的
  8.  * 内容被一起flush出来。
  9.  *
  10.  * 加上func后,执行结果如下:
  11.  * [root@localhost apue.2e]# ./fig8-1
  12.  * pid:3257, cnt:1
  13.  * a write to stdout
  14.  * before fork
  15.  * pid:3258, cnt:2
  16.  * pid:3258, cnt:3
  17.  * pid = 3258, glob = 7, var = 89
  18.  * pid:3257, cnt:2
  19.  * pid:3257, cnt:3
  20.  * pid = 3257, glob = 6, var = 88
  21.  *
  22.  * func()里的cnt也是放在数据段的?
  23.  */

  24. #include "apue.h"

  25. int glob = 6; /* external variable in initialized data */
  26. char buf[] = "a write to stdout\n";

  27. static void func()
  28. {
  29.     static int cnt = 0;

  30.     cnt ++;
  31.     printf("pid:%d, cnt:%d\n", getpid(), cnt);

  32.     return;
  33. }

  34. int
  35. main(void)
  36. {
  37.     int var; /* automatic variable on the stack */
  38.     pid_t pid;

  39.     var = 88;

  40.     func();

  41.     if (write(STDOUT_FILENO, buf, sizeof(buf)-1) != sizeof(buf)-1)
  42.         err_sys("write error");
  43.     printf("before fork\n"); /* we don't flush stdout */

  44.     if ((pid = fork()) < 0) {
  45.         err_sys("fork error");
  46.     } else if (pid == 0) { /* child */
  47.         glob++; /* modify variables */
  48.         var++;
  49.     } else {
  50.         sleep(2); /* parent */
  51.     }

  52.     func();
  53.     func();

  54.     printf("pid = %d, glob = %d, var = %d\n", getpid(), glob, var);
  55.     exit(0);
  56. }
阅读(703) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~