Chinaunix首页 | 论坛 | 博客
  • 博客访问: 584369
  • 博文数量: 70
  • 博客积分: 3736
  • 博客等级: 中校
  • 技术积分: 1728
  • 用 户 组: 普通用户
  • 注册时间: 2008-07-08 09:15
文章分类
文章存档

2014年(1)

2012年(21)

2011年(7)

2010年(28)

2009年(13)

分类: LINUX

2012-01-18 10:45:08

example1.c
  1. #include
  2. void main()
  3. {
  4. char *ptr;
  5. int c;
  6. while((c = getchar()) != EOF)
  7. putchar(c);
  8. }
运行:
# strace ./example1
  1. ...
  2. read(0, 123456
  3. "123456\n"..., 1024) = 7
  4. fstat64(1, {st_mode=S_IFCHR|0620, st_rdev=makedev(136, 1), ...}) = 0
  5. mmap2(NULL, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0xb80a9000
  6. write(1, "123456\n"..., 7123456
  7. ) = 7
  8. ...
由于stdout默认是行缓冲的,所以putchar仅仅是把字符保存在缓冲区中,当碰到换行符时才一次性调用write写出
example2.c
  1. #include
  2. void main()
  3. {
  4. char *ptr;
  5. int c;
  6. setbuf(stdout, NULL);
  7. while((c = getchar()) != EOF)
  8. putchar(c);
  9. }
运行:
#strace ./example2
  1. ...
  2. read(0, 123456
  3. "123456\n"..., 1024) = 7
  4. write(1, "1"..., 11) = 1
  5. write(1, "2"..., 12) = 1
  6. write(1, "3"..., 13) = 1
  7. write(1, "4"..., 14) = 1
  8. write(1, "5"..., 15) = 1
  9. write(1, "6"..., 16) = 1
  10. write(1, "\n"..., 1
  11. ) = 1
  12. ...
在本例中,将stdout修改为不带缓冲,所以,每次putchar都会激发系统调用write
example3:
  1. #include
  2. void main()
  3. {
  4. char buf[1024];
  5. char *ptr;
  6. while((ptr = gets(buf)) != EOF)
  7. puts(buf);
  8. }
运行:
#strace ./example3
  1. ...
  2. read(0, 123456
  3. "123456\n"..., 1024) = 7
  4. fstat64(1, {st_mode=S_IFCHR|0620, st_rdev=makedev(136, 1), ...}) = 0
  5. mmap2(NULL, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0xb8027000
  6. write(1, "123456\n"..., 7123456
  7. ) = 7
  8. ...
puts将一个以null符终止的字符串写到标准输出,终止符不写出,但是puts在字符串后面添加换行符(若字符串本身已有换行符,则不会重复添加)
example4:
  1. #include <stdio.h>
  2. void main()
  3. {
  4.     char buf[1024];
  5.     char *ptr;
  6.     setbuf(stdout, NULL);
  7.     while((ptr = gets(buf)) != EOF)
  8.         puts(buf);
  9. }
运行:strace ./example4
  1. ...
  2. read(0, 123456
  3. "123456\n"..., 1024) = 7
  4. write(1, "123456"..., 6123456) = 6
  5. write(1, "\n"..., 1
  6. ) = 1
  7. ...
这种输出说明了什么呢?待解!
阅读(1412) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~