Linux命令源代码阅读yes

来源:互联网 发布:linux查看资源使用情况 编辑:程序博客网 时间:2024/05/29 03:20

Linux下有一个yes命令,在终端循环输出一行字符,直到被信号打断。代码中用到一个叫BUFSIZ的宏,这个宏很有意思,指的是系统默认输出到屏幕的缓冲区大小,在stdio.h头文件中定义。

可以使用man setbuf来查看3种缓冲方式的区别:

/* The  three types of buffering available are unbuffered, block buffered,and line buffered.  When an output stream  is  unbuffered,  informationappears on the destination file or terminal as soon as written; when itis block buffered many characters are saved up and written as a  block;when  it  is  line  buffered characters are saved up until a newline isoutput or input is read from any stream attached to a  terminal  device(typically  stdin).   The  function  fflush(3) may be used to force theblock out early.  (See fclose(3).)Normally all files are block buffered.  If a stream refers to a  termi‐nal (as stdout normally does), it is line buffered.  The standard errorstream stderr is always unbuffered by default. */
三种可用的缓冲方式分别是:不缓冲、块缓冲、行缓冲。

正常情况下:文件都是块缓冲;涉及到终端的流是行缓冲;标准出错流默认不缓冲。

setbuf用来制定某个流使用某个缓冲区

例如man手册中的例子:

/*You must make sure that the space that buf points to  still  exists  bythe  time  stream is closed, which also happens at program termination.必须保证buf指向的空间在流关闭之前仍然存在;程序结束时,流也会关闭For example, the following is invalid:*/#include <stdio.h>intmain(void){char buf[5];setbuf(stdout, buf);//所有写入到stdout的输出都应该使用buf作为输出缓冲区printf("Hello, world!\n");return 0;}
这个例子使用setbuf不正确,因为在main函数结束时(执行完return语句),栈中的buf自动回收,程序的入口点(运行库一部分)进行清理工作时,buf已经不在了,是不能把内容显示出来的。这样的话buf就不要放在main函数的栈中,可以放到堆或者.data.bss中。

其中运行库中的程序入口点实在main()执行前做初始化工作,在将要执行右大括号(main函数结束)时进行回收工作。具体可以看程序员自我修养关于运行库一章。