日历
网志分类
· 所有网志 (20)
· RFC (2)
· NAT (4)
· VB (1)
· IPv6 (1)
· KAME NAT-PT (2)
· 未分类 (10)
最新的评论
站内搜索
友情链接
· Ycool
· immicf
· Internet RFC/STD/FYI/BCP Archives
· 网络精英联盟
· Developer Fusion
· 网络协议分析论坛
· VB语言参考
· Network Room

订阅 RSS

0006773

歪酷博客

fcimmi

CS notes


immicf @ 2010-02-10 11:44

Note: Stanislav Shalunov wrote an excellent article on TCP over WAN Performance Tuning and Troubleshooting. In this series of articles, I want to summarize his findings and provide tuning suggestions for popular operating systems.

Most operating systems today ship with TCP stacks optimized for either LAN (high speed, low latency) or broadband (low speed, high latency) traffic. In the case of statewide or nationwide networks, these settings fail miserably. For example, on a statewide network connected via an OC3, a FreeBSD server with default settings will only get about 13 Mbps. On a nationwide network connected via DS3, a Mac mini gets only 8 Mbps with default settings.

TCP uses the Slow Start and Congestion Avoidance algorithms to determine how many packets can be transmitted between the sender and receiver. This is usually expressed in terms of the congestion window. The congestion window is the maximum amount of data that can be transmitted without receiving an acknowledgment from the receiver. If an acknowledgment isn’t received, TCP assumes there is congestion on the network and slows down the packet transmission. In a high-speed, high-latency network, the default window size in most operating systems causes TCP to scale back the transmission rate. With a larger window size, the receiver has a chance to acknowledge the incoming packets and the high-speed transmission is maintained.

To determine how much throughput can be expected, take the window size and divide it by the RTT in seconds. The chart below shows the calculations for various window sizes and and RTTs.

Throughput (Mbps)
Window Size RTT 20ms RTT 60ms RTT 80ms Note
8 KB 3.3 1.1 0.8
16 KB 6.6 2.2 1.6 Linux 2.6, Windows default
32 KB 13.1 4.4 3.3 FreeBSD, Mac OS X default
64 KB 26.2 8.7 6.6
128 KB 52.4 17.5 13.1
256 KB 104.9 35.0 26.2
512 KB 209.7 69.9 52.4
1 MB 419.4 139.8 104.9
2 MB 838.9 279.6 209.7
It seems obvious that increasing the TCP window size is a necessary modification. Care must be taken to not increase the window size too large. If so, the system may run out of memory. A good rule of thumb is to set the window size to 1 MB.

What is TCP Window Scaling?

The original TCP specification included a window size no larger than 64 KB. This limitation was introduced by the 16 bit header that specified window size. To achieve the recommended 1 MB window size, RFC 1323 TCP extensions must be enabled. The rest of this post is a somewhat detailed elaboration of how the RFC 1323 TCP window scaling option works.

The TCP window scaling option in RFC 1323 allows for a maximum window size of 1 GB. This particular limitation is derived from the original design of TCP that requires a data segment’s sequence number to be within the first 231 bytes (2 GB) of the window. If the sequence number does not appear in that area, the data segment is considered old and discarded. To guarantee the sequence number is always withing the first 231 bytes, RFC 1323 requires the maximum window size to be less than 230 bytes.

The TCP window scaling option works by including a scale factor in a SYN packet. This scale factor informs the receiver that the sender is willing to do window scaling and offers a scale factor for the communication. The scale factor is used to shift the window field before the data segment is sent. The scale factor is limited to 14 to guarantee the window is less than the 231 maximum. Thus, 2^14 * (2^16 - 1) < 2^31 (or (2^16 - 1) << 14 < 2^31, if you prefer).

All of this is just a highly involved way of saying that in order to increase window size beyond the 64 KB limit, RFC 1323 window scaling options must be enabled. Most operating systems support this option, but not all of them have it enabled by default. When in doubt, make sure and enable it.

TCP Performance Tuning and Broken Routers

In TCP window scaling and broken routers posted in July of 2004, LWN.net’s corbet points out that certain routers are setting the RFC 1323 window scale to 0. This effectively sets the TCP window size for the transmission to the minimum value and greatly inhibits performance. As corbet notes, Linux kernel developers have decided not to apply a band aid to the problem, and instead plan to force router manufacturers to fix their broken routers.

In case there are still broken routers floating around, it’s worth noting that in recent versions of the Linux kernel, the window size can be controlled on a per host basis. See the comment by pcharlan for the necessary syntax.
If you should run across a router that is affecting your window scaling, you should immediately put pressure on the provider to remove the offending device.

FreeBSD TCP Performance Tuning

To enable RFC 1323 Window Scaling and increase the TCP window size to 1 MB on FreeBSD, add the following lines to /etc/sysctl.conf and reboot.

net.inet.tcp.rfc1323=1
kern.ipc.maxsockbuf=16777216
net.inet.tcp.sendspace=1048576
net.inet.tcp.recvspace=1048576

You can make these changes on the fly via the sysctl command. As always, the ‘$‘ represents the shell prompt and should not be typed.

$ sudo sysctl net.inet.tcp.rfc1323=1
$ sudo sysctl kern.ipc.maxsockbuf=16777216
$ sudo sysctl net.inet.tcp.sendspace=1048576
$ sudo sysctl net.inet.tcp.recvspace=1048576

In addition, FreeBSD may have a low number of network memory buffers (mbufs) by default. You can view the current mbuf configuration by running netstat -m. If your mbuf value is too low, it may cause your system to become unresponsive to the network. Increase the number of mbufs by adding the line below to /boot/loader.conf and rebooting.

kern.ipc.nmbclusters="16384"

Note: a reboot is required to increase the number of mbufs.

Linux TCP Performance Tuning

If you have been following our TCP Performance Tuning series, you’ll know that we want to enable RFC 1323 Window Scaling and increase the TCP window size to 1 MB. To do this, we’ll add the following lines to /etc/sysctl.conf and issue sudo sysctl -p to apply the changes immediately.

net.core.rmem_max = 16777216
net.core.wmem_max = 16777216
net.core.rmem_default = 1048576
net.core.wmem_default = 1048576
net.ipv4.tcp_rmem = 4096 1048576 16777216
net.ipv4.tcp_wmem = 4096 1048576 16777216
net.ipv4.tcp_congestion_control = bic
net.ipv4.tcp_window_scaling = 1
net.ipv4.tcp_timestamps = 1

As before, we’re setting the maximum buffer size large and the default window size to 1 MB. RFC 1323 is enabled via net.ipv4.tcp_window_scaling and net.ipv4.tcp_timestamps. These options are probably on by default, but it never hurts to force them via /etc/sysctl.conf. Finally, we are choosing BIC as our TCP Congestion Control Algorithm. Again, that value is most likely the default on your system (especially any kernel version after 2.6.12).

Mac OS X TCP Performance Tuning

Because Darwin is BSD-based, it’s no surprise that Mac OS X TCP Performance Tuning is very similar to FreeBSD TCP Performance Tuning. Although RFC 1323 TCP Extensions should be enabled by default, it doesn’t hurt to force them on. Also, we’ll set the TCP send and receive window sizes to 1 MB.

Mac OS X does not include /etc/sysctl.conf, so you’ll need to create it. Once that’s done, add the following lines and reboot.

net.inet.tcp.rfc1323=1
kern.ipc.maxsockbuf=16777216
net.inet.tcp.sendspace=1048576
net.inet.tcp.recvspace=1048576

You can avoid rebooting by issuing the following commands: (As always, the ‘$‘ represents the shell prompt and should not be typed.)

$ sudo sysctl -w net.inet.tcp.rfc1323=1
$ sudo sysctl -w kern.ipc.maxsockbuf=16777216
$ sudo sysctl -w net.inet.tcp.sendspace=1048576
$ sudo sysctl -w net.inet.tcp.recvspace=1048576

Unlike FreeBSD, Mac OS X has plenty of network memory buffers (mbufs) by default.

Solaris TCP Performance Tuning

As we have throughout the TCP Performance Tuning series, we’re going to make sure RFC 1323 Window Scaling is enabled and increase our send and receive window size to 1 MB. The ndd command is the Solaris equivalent of sysctl in FreeBSD/Linux/Mac OS X. As always, the ‘$‘ represents the shell prompt and should not be typed.

$ sudo ndd -set /dev/tcp tcp_wscale_always 1
$ sudo ndd -set /dev/tcp tcp_tstamp_if_wscale 1
$ sudo ndd -set /dev/tcp tcp_max_buf 16777216
$ sudo ndd -set /dev/tcp tcp_cwnd_max 8388608
$ sudo ndd -set /dev/tcp tcp_xmit_hiwat 1048576
$ sudo ndd -set /dev/tcp tcp_recv_hiwat 1048576

To make these settings permanent, add the following lines to /etc/system.

set ndd:tcp_wscale_always=1
set ndd:tcp_tstamp_if_wscale=1
set ndd:tcp_max_buf=16777216
set ndd:tcp_cwnd_max=8388608
set ndd:tcp_xmit_hiwat=1048576
set ndd:tcp_recv_hiwat=1048576

By default, Solaris has RFC 1323 Window Scaling and Timestamps enabled, but it never hurts to make sure.

Windows TCP Performance Tuning

As discussed previously, we’re going to enable RFC 1323 Window Scaling and increase the default TCP receive and send windows to 1 MB. By default Windows 2000 and XP do not offer window scaling options, but will accept them if offered by the other side. To make our changes, we’ll need to modify the following registry keys under HKLM\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters and reboot the system.

Tcp1323Opts = 3
TcpWindowSize = 1048576
GlobalMaxTcpWindowSize = 16777216

You can edit the Windows registry with Registry Editor. To start Registry Editor issue regedit at the command prompt or in the Run box. In this image, you can see the various options being set. Remember to select the radio option for Decimal, otherwise your values won’t mean what they should.


 
immicf @ 2009-04-11 14:57

Predefined Types and Values - FILE, EOF, NULL and size_t

  • FILE is a datatype which holds information about an open file.
  • EOF is a value returned to indicate end-of-file (though is not used exclusively for that purpose) and is required by ANSI C to be a negative integral constant expression and is traditionally set to -1.
  • NULL is set to the value of the null pointer constant 0
  • BUFSIZ is an integer constant which specifies an "appropriate" size for file I/O buffers.
  • size_t is an unsigned integral type which is large enough to hold any value returned by sizeof

Preopened File Streams - stdin, stdout, and stderr

  • FILE *stdin
    • stdin is associated with a user's standard input stream.
  • FILE *stdout
    • stdin is associated with an output stream used for normal program output.
  • FILE *stderr
    • stdin is associated with an output stream used for error messages.

Open File - fopen and freopen

  • FILE *fopen(const char *path, const char *mode)
    • fopen opens the file designated by the character string path and associates it with a stream. The mode string should begin with one of the following sequences:
      • r - open an existing file for reading, starting at the beginning of the file.
      • w - truncate an existing file to zero length or create a text file for writing, starting at the beginning of the file.
      • a - open or create for writing at end of text file.
      • r+ - open an existing file for reading and writing, starting at the beginning of the file.
      • w+ - truncate an existing file to zero length or create a text file for reading and writing, starting at the beginning of the file.
      • a+ - open for reading and writing at end of file or create for reading and writing.
    • The mode string may include a b as either the second or third character to indicate a binary file.
    • The mode string may also contain other characters after the above modes, which are used in an implementation-defined manner.
    • If a file is opened for update (the + mode), an output operation may not be followed by an input operation without flushing the buffer (fflush())) or repositioning (fseek(), fsetpos, rewind), and an input operation may not be followed by an output operation without flushing the buffer or repositioning unless the input operation has reached end-of-file.
    • If fopen succeeds, a FILE pointer is returned. Otherwise, NULL is returned and errno is set.
  • FILE *freopen(const char *pathname, const char *mode, FILE *stream)
    • freopen behaves exactly like fopen except that it associates the newly opened file with stream rather than creating a new stream.
    • freopen is primarily used to associate a new file with one of the standard text streams (stdin, stdout, or stderr).

Flush File Buffer - fflush

  • int fflush(FILE *stream)
    • fflush forces any buffered output to be written, but does not close the stream.
    • If stream is a null pointer, fflush flushes all of a process' open output streams (at least on UNIX systems)
    • If the operation succeeds, fflush returns 0. Otherwise, EOF is returned and errno is set.

Close File - fclose

  • int fclose(FILE *stream)
    • fclose causes any buffered output to be written (possibly using fflush) and then closes the stream.
    • Subsequent attempts to use stream in any routine other than freopen will result in errors.
    • If the operation succeeds, fclose returns 0. Otherwise, EOF is returned and errno is set.

Check or Clear File Status - feof, ferror and clearerr

  • int feof(FILE *stream)
    • feof checks the end-of-file indicator for stream and returns non-zero if it is set.
    • Note that even if the last character in a file has been read, an end-of-file condition does not exist until a request is made to read the character after the last character.
  • int ferror(FILE *stream)
    • ferror checks the error indicator for stream and returns non-zero if it is set.
  • void clearerr(FILE *stream)
    • clearerr clears the end-of-file and error indicators for stream.
    • Once an end-of-file or error indicator has been set, it is not reset until clearerr is called (with the exception that file repositioning functions clear the end-of-file indicator.)

Read Character from File - getc, fgetc and getchar

  • int fgetc(FILE *stream)
    • fgetc reads the next available character from the input stream stream and returns it as an int
  • int getc(FILE *stream)
    • getc is identical in function to fgetc but is usually implemented as a macro (which means that stream may be evaluated more than once, so it should not be an expression with side effects.)
  • int getchar(void)
    • getchar reads the next available character from stdin and is typically implemented as getc(stdin) (which means it is a macro with all the problems of getc.)
  • Errors and End-Of-File
    • If stream or stdin is at end-of-file or a read error occurs, these routines return EOF (and errno is set if an error occurs.) feof or ferror must therefore be used to distinguish between the two conditions.

Write Character to File - putc, fputc and putchar

  • int fputc(int c, FILE *stream)
    • fputc writes c to the output stream stream as an unsigned char and returns the character as an int. If an error occurs, EOF is returned and errno is set.
  • int putc(int c, FILE *stream)
    • putc is identical in function to fputc but is usually implemented as a macro (which means that stream and c may be evaluated more than once, so they should not be expressions with side effects.)
  • int putchar(int c)
    • putchar writes c to stdout and is typically implemented as putc(stdout) (which means it is a macro with all the problems of putc.)

Push Character Back into Buffer - ungetc

  • int ungetc(int c, FILE *stream)
    • ungetc pushes c back onto the input stream stream, so that it will be returned by a subsequent read of stream.
    • Pushed back characters are read in reverse order.
    • If a file repositioning function (fseek(), fsetpos, rewind) is used, any pushed back characters are lost.
    • ungetc does not affect the contents of the file pointed to by stream
    • One character of pushback is guaranteed.
    • Attempts to push EOF have no effect on stream and return EOF

Read String from File - fgets and gets

  • char *fgets(char *s, int n, FILE *stream)
    • fgets reads characters from stream and stores them in the string pointed to by s.
    • Reading stops when a newline character is seen, end-of-file is reached or n-1 characters have been read, and '{post.abstract}'s (after any newline character.) is appended to
    • If end-of-file occurs before any characters have been read, fgets returns NULL and the contents of s are unchanged.
    • If an error occurs at any time during the read operation, fgets returns NULL and the contents of s are undefined.
    • Otherwise, fgets returns s
  • char *gets(char *s, FILE *stream)
    • gets is similar to fgets, but is much more dangerous.
      • gets does not store a newline character.
      • More importantly, gets assumes that s is infinitely long, allowing sufficiently knowledgeable programmers to worm their way inside the program.

Write String to File - fputs and puts

  • int fputs(const char *s, FILE *stream)
    • fputs writes the null-terminated string s to the output stream stream.
    • If an error occurs, fputs returns EOF. Otherwise, is returns a nonnegative integer.
  • int puts(const char *s)
    • puts writes the null-terminated string s, followed by a newline character, to the stdout output stream.

Read Binary Data from File - fread

  • size_t fread(void *ptr, size_t siz, size_t num, FILE *stream)
    • fread reads up to num objects, each siz bytes long, from input stream stream, storing them in the memory pointed to by ptr.
    • The number of objects read is returned.
    • If an error occurs, zero will be returned.
    • If end-of-file is reached, the value returned will be less than num (and may be zero, in which case feof or ferror should be used to distinguish between the two conditions.)

Write Binary Data to File - fwrite

  • size_t fwrite(const void *ptr, size_t siz, size_t num, FILE *stream)
    • fwrite writes up to num objects, each siz bytes long, from the memory pointed to by ptr to the output stream stream.
    • The number of objects written is returned.
    • If an error occurs, zero will be returned.

Read Formatted Input - scanf, fscanf, sscanf

  • int scanf(const char *format, ...)
  • int fscanf(FILE *stream, const char *format, ...)
  • int sscanf(const char *str, const char *format, ...)

Write Formatted Output - printf, fprintf, sprintf

  • int printf(const char *format, ...)
  • int fprintf(FILE *stream, const char *format, ...)
    • fprintf writes to output stream stream.
  • int sprintf(const char *str, const char *format, ...)
    • sprintf "writes" its output to the character string str (followed by a terminating '{post.abstract}'.)
  • All three functions return the number of characters written (not including the terminating '{post.abstract}' for sprintf)

File Position - fgetpos, fsetpos, rewind, fseek, and ftell

  • int fgetpos(FILE *stream, fpos_t *pos);
    • fgetpos stores the value of the current file position indicator for stream in pos.
    • pos is an implementation-defined type which may be integral or may be a complex structure.
    • If an error occurs, a non-zero value is returned and errno is set.
  • int fsetpos(FILE *stream, fpos_t *pos)
    • fsetpos sets the file position indicator for stream to the position indicated by pos.
    • If an error occurs, a non-zero value is returned and errno is set.
    • If fsetpos succeeds, the end-of-file indicator is cleared.
  • void rewind(FILE *stream)
    • rewind sets the file position indicator for stream to the beginning of the file.
  • int fseek(FILE *stream, long offset, int whence)
    • fseek sets the file position indicator for stream. The new byte position is obtained by adding offset to the position specified by whence:
      • If whence is set to SEEK_CUR, the offset is computed from the current position in the file.
      • If whence is set to SEEK_SET, the offset is computed from the beginning of the file.
      • If whence is set to SEEK_END, the offset is computed from the end of the file.
        • SEEK_CUR, SEEK_SET, and SEEK_END are all defined in <stdio.h>.
    • fseek is usually applied to binary files.
  • long ftell(FILE *stream)
    • ftell returns the current file position for stream.
    • For binary files, the value returned is the number of bytes from the beginning of the file to the current file position.
    • For text files, the value is implementation-defined, but is guaranteed to be useable in fseek and 0L must represent the beginning of the file.

Alter File Buffer Size - setbuf and setvbuf

  • void setvbuf(FILE *stream, char *buf, int buftype, size_t bufsize)
    • setvbuf sets the type, size and location of the buffer for stream.
    • The three types of buffering available are:
      • _IOFBF causes I/O to be block buffered, meaning that bytes are saved up and written when bufsize has been reached.
      • _IOLBF causes I/O to be line buffered, meaning that the buffer is written when either a newline character is saved to the buffer or when bufsize has been reached.
      • _IONBF means that no buffering is done; everything is immediately written.
    • If buf is non-null, it is assumed to be at least bufsize bytes long and will be used instead of the automatically created buffer.
      • The predefined constant BUFSIZ is the recommended value for the buffer size.
      • If buf is NULL, the stream is completely unbuffered.
    • setvbuf can safely be called after a stream has been opened but before any data are read or written.
    • setvbuf returns EOF on error.
  • void setbuf(FILE *stream, char *buf)
    • setbuf has the same effect as
      setvbuf(stream, buf, buf ? _IOFBF : _IONBF, BUFSIZ);

Temporary File Functions - tmpfile and tmpnam

  • FILE *tmpfile(void)
    • tmpfile attempts to create a new file and open it using mode wb+.
    • If the create and open succeed, a FILE pointer is returned.
    • If the file could not be opened, NULL is returned.
    • The file is automatically deleted when it is closed or when the process terminates.
    • Note that this function may create a file which is publicly readable and writable.
  • char *tmpnam(char *str)
    • tmpnam generates a temporary file name which was not in use when tmpnam was called.
    • If str is non-null, the file name is copied to that buffer.
      • str is expected to be at least L_tmpnam characters long.
    • If str is null, a static buffer is used, meaning that subsequent calls to tmpnam may overwrite the buffer.
    • Temporary file names use the path prefix P_tmpdir.
    • Both L_tmpnam and P_tmpdir are defined in <stdio.h>.
    • tmpnam is guaranteed to be able to generate at least TMP_MAX unique temporary file names, where TMP_MAX must be at least 25.
    • Note that there is a race condition between file name selection and file creation.
    • Note also that tmpnam does not create the file and therefore does not ensure the file will be deleted after the program is terminated.


 
immicf @ 2009-04-10 07:08

第三章

带缓冲的I/O

由第一章我们知道,一个文件系统可以抽象为块,块是 I/O 世界的通用语。所有的磁盘操作在某种意思上都是对块进行的。
因此,如果我们能按块大小的整数倍来对齐,从而对 I/O 进行读写操作,那么操作的性能能达到最佳。

增加用于读写的系统调用次数会使性能急剧退化,比如说读1024次每次字节,跟一次性读1024字节相比,后者性能好得多。
甚至一连串对尺寸大于一个块的操作,其性能也是欠佳的,如果每次操作的尺寸不是块大小的整数倍。比如,假设块大小为
1k 字节,选1,130字节作为一欠操作的整块,仍然会比选1,024字节的操作慢。


用户态带缓冲的I/O

那些需要对一般文本进行多次轻量级I/O访问的程序往往应用用户态的带缓冲I/O。
这涉及到用户态的缓冲而不是由内核处理的缓冲,这种缓冲一般由程序人工地或者由库透明地执行。
就像我们在第2章讲过的,为了提高性能,内核会在底层通过缓写和预读来进行数据缓冲。
虽然手段不同,但用户态缓冲机制也是为了提高性能。

考虑一个在用户态执执行程序 dd 的例子:

dd bs=1 count=2097152 if=/dev/zero of=pirate

因为参数 bs = 1,这个命令会从设备 /dev/zero(一个能提供源源不断 0 的虚拟设备)拷贝 2Mbs 到文件pirate,
其形式是2,097,152个字节块。也就是说,它会执行两百万次读和写的操作,每次一个字节。

现在考虑同关2Mbs数据的拷贝,不同的是以1,024字节作为块大小:
dd bs=1024 count=2048 if=/dev/zero of=pirate

该操作拷贝同样 2Mbs 数据至同一个文件,但是只进行了1,024次读和写。
从表3-1可以看到,性能得到了很大提高。
表中,我记录了4次 dd 命令所消耗的时间(通过三种不同的方式),它们的区别仅仅是块的大小。
real time 是程序开始执行到退出花的时间,user time 是用户态执行该程序的时间,system time 是在内核态执行系统调用的时间。

表3-1. 块大小对性能的影响
Block size    Real time     User time     System time
1 byte     18.707 seconds   1.118 seconds  17.549 seconds
1,024 bytes   0.025 seconds   0.002 seconds  0.023 seconds
1,130 bytes   0.035 seconds   0.002 seconds  0.027 seconds


用1,024字节作为块大小与仅仅用1个字节作为块大小相比,前者能大副度提高性能。
然而,上表也表明虽然用大尺寸能减少系统调用,但也有可能会使性能退化,如果这个尺寸不是磁盘块大小的整数倍的话。
尽管1,130字节的需要更少的系统调用,但是它的读写请求最终会产生未对齐的读写请求,
这样的话会使它不如1,024字节的读写请求那么高效。

要想利用这种性能的恩赐,我们需要预先知道很相近的物理块大小。
上表表明这个数字很可能是1,024的整数倍或者能被1,024整除。
在例子 /dev/zero 中,块的大小实际上是4,096字节。


块大小

通常,块大小一般是 512, 1,024, 2,048, 或 4,096 字节。

表3-1表明,以块大小的整数倍或因子为单位进行读写操作,可以取得很好的性能。
这是因为内核和硬件是以块作为语言来进行交流的。因此,以块大小或一个能很整洁安排块的大小为单位,
这样可以保证块对齐的要求,从而避免内核做些雍余的工作。

用系统调用 stat()(见第7章) 或 命令stat(1) 可以很简单地算出给定设备的块大小。
然而大多数时候我们并不需要知道准确的块大小。

当你为 I/O 操作选一个合适的大小时,最重要的目标是不要选类似 1,130 这么蹩脚的数字。
在 Unix 历史上,从来没有块大小为1,130字节的。
选这样的大小会使你第一次以后的读写操作都对不齐。
选择块大小的因子或整数倍,可以防止未对齐的请求。
只要选择的大小能使一切都以块对齐,那么就能得到好的性能,
选择更大整数倍的只会简单地减少系统调用的次数。


User-Buffered I/O | 63

因此,最简单的做法是选典型块大小的整数倍来进行 I/O 操作,比如4,096和8,192字节都不错。

当然,问题在于很少有程序从块的角度出发。大多程序是与域,行以及单个字符打交道的,而不是抽象的块。
如前所述,为了补救这种状况就引入了用户态缓冲机制的I/O。
将要被写的数据会先存入在一个缓冲区里,这个缓冲区位于程序的地址空间。
当缓冲区里的数据大小达到特定的尺寸(缓冲大小)时,整个缓冲区里的内容会被单独的一个写操作写出。
同样的,数据被读入时也是按照块对齐的缓冲区大小进行的。
随着程序响应它尺寸冏异的读请求,大块的缓冲区被一片片瓜分。
最终,当瓜分殚尽时,按块对齐的另一大块数据会被读入缓冲区。
如果缓冲区大小合适的话,可以获得良好的性能效益。

在你的程序里手动实现用户缓冲寄存器是不是不可能的。
其实很多紧要使命的程序正是这么做的。
然而,大多数程序还是利用了流行的标准I/O库(标准C库的一部分),
它提供了一个良好的鲁棒性和功能强大的用户态缓冲机制解决方案。

标准 I/O 库

C标准库提供了标准 I/O 库,通常简称为 stdio,standard I/O library。
stdio反过来又提供了一个与平台无关的用户态缓冲机制解决方案。

不像 FORTRAN 之类的编程语言,除了流控制,算术之类的功能外,
C语言没有对其他更高级的功能提供内置的支持或关键字。
当然也不会对I/O有任何固有支持。
随着C语言的发展,用户开发了一些标准的例程集来提供核心功能,比如字符串处理,数学函数,
时间和日期功能,以及I/O等。
随着时间的过去,这些例程也慢慢成熟了,最终在1989年通过了 ANSI C 标准(C89)的认可,从而成为标准C 库的一部分。
尽管 C95 和 C99 都加了一些新的接口,但标准 I/O 库自从1989年制定以来相对来说没有改变过。

本章剩下的篇幅来讨论用户态缓冲机制的 I/O ,因为它是属于文件 I/O 的,并且是由 C语言标准库实现的。
也就是说文件的打开,关闭,读写的实现都借助于 C 语言标准库。
一个程序是否使用标准 I/O,这个home-rolled? 或者进行系统调用?
开发者要认真权衡程序的需求和行为才能做决定。

C标准总是为每个函数的实现留下一些可扩充的细节,这些函数往往被添加其他功能。
本章包括以后章节中,整理归档了在现代linux系统中,glibc实现的一些接口和行为。
凡是Linux偏离基本标准的地方,会作出提示。


64 | Chapter 3: Buffered I/O

文件指针

标准 I/O 例程不直接操作的文件描述符。
相反,它们利用自己独特的标识,称为文件指针。
在C库中,文件指针映射到文件描述符。
文件指针被表示为指针FILE,它由typedef定义在<stdio.h>中。

在标准I/O里,一个打开的文件被称为流。
流可以打开进行读(输入流),写(输出流) ,或两者兼施(输入/输出流) 。


打开文件

fopen()用来打开文件从而进行读或写操作。
#include <stdio.h>

FILE * fopen (const char *path, const char *mode);

该函数根据给定的模式mode来打开文件path,然后把它和一个流绑定起来。

模式 mode

参数mode指定了怎么打开一个文件,它可以是以下几种:

r
打开文件进行读操作。流指向文件的开始位置。

r+
打开文件进行读和写操作。流指向文件的开始位置。

w
打开文件进行写操作。如果文件已经存在,就把它的长度截断为0。
如果文件不存在,就创建一个新的。流指向文件的开始位置。

w+
打开文件进行读和写操作。如果文件已经存在,就把它的长度截断为0。
如果文件不存在,就创建一个新的。流指向文件的开始位置。

a
打开文件进行追加操作。如果文件不存在,就创建一个新的。流指向文件的尾部。
所有的写操作都会附加到文件。

a+
打开文件进行读以及追加操作。如果文件不存在,就创建一个新的。流指向文件的尾部。
所有的写操作都会附加到文件。
Opening Files | 65

给定的模式也可能包含的字母b,虽然这个值总是被 Linux 忽略.
有些操作系统处理文本文件和二进制文件是不同的,而模式b可以用来指示以二进制模式打开文件。
和所有符合POSIX的系统一样,Linux完全等同地对待文本文件和二进制文件。

一旦成功, fopen()函数返回一个有效的文件指针。
如果失败,则返回 NULL,并设置相应的errno。

例如,下面的代码打文件 /etc/mainfest 进行读操作,并且将它跟流绑定起来。
FILE *stream;

stream = fopen ("/etc/manifest", "r");

if (!stream)

/* error */

通过文件描述符打开流

函数fdopen()可以将一个已经打开的文件描述符(fd)转化为一个流。

#include <stdio.h>

FILE * fdopen (int fd, const char *mode);

函数可以使用的的模式mode同fopen(),而且要符合原本用来打开文件描述符的模式。
需要指明的是 w 和 w+ 不会截断文件。
流在文件中的位置跟文件描述符相关。

一旦一个文件描述符被转化为一个流,I/O不应该再直接操作那个文件描述符(尽管这种做法是合法的)。
请注意,原来的文件描述符不会被复制,而仅仅是与一个新的流绑定起来。
关闭这个流也将关闭相应的文件描述符。

执行成功的话,fdopen()返回一个有效的文件指针;失败则返回 NULL。
比如,下面的代码用系统调用open()打开文件 /home/kidd/map.txt,
然后利用之前的文件描述符建立一个与之相关的流。
FILE *stream;
int fd;


fd = open ("/home/kidd/map.txt", O_RDONLY);

if (fd == &#8722;1)

/* error */

stream = fdopen (fd, "r");

if (!stream)

/* error */

66 | Chapter 3: Buffered I/O

关闭流


函数fclose()用来关闭一个流:
#include <stdio.h>

int fclose (FILE *stream);

fclose函数将所有未写入的数据写入stream中,如果出错则返回EOF,并设置相应的errno.


关闭所有流

fcloseall函数关闭与目前进程相关的所有流,包括stdin,stdout,stderr.

#define _GNU_SOURCE

#include <stdio.h>

int fcloseall (void);

在关闭之前,所有的流都会被刷新,该函数总是返回0,这是linux特色。

从一个流中读数据

C标准库实现了很多函数从一个打开的文件中读数据,有常用的,也用罕见的。
本节将讨论其中三个最常用的:一次读入一个字符,一次读一行,以及读二进制数据。
要想从一个流中读数据,这个流在打开时所用的模式必须是有效的,也就是说除了w和a之外的其他模式。

一次读入一个字符

通常情况下,理想的I/O模型是简单地一次只读一个字符。
函数fgetc()刚好实现了这个功能。

#include <stdio.h>

int fgetc (FILE *stream);

该函数返回stream流的下一个字符,返回类型为unsigned char,然后被转换为int类型。
这个类型转换只为了给出错时返回的EOF留出足够的空间范围.
fgetc()的返回值必须存在int里,如果把它存在一个char里将是一个常见但危险的错误。

Reading from a Stream | 67
-----------------------------------

下面的例子从stream中读入一个字符,检查错误,然后以字符格式打印出来:
int c;

c = fgetc (stream);

if (c == EOF)

/* error */

else

printf ("c=%c\n", (char) c);

当然,stream指向的流必须是以可读模式打开的。

把一个字符压回流中


标准I/O提供了一个函数将一个已读的字符放回流中,该功能使你能够“偷窥”一下,
如果流中下一个字符不是你想要的,你还可以把它放回流中。

#include <stdio.h>

int ungetc (int c, FILE *stream);

每次调用该函数都会把 c 强转为unsigned char, 然后压回去流中。
如果调用成功,则返回c;失败则返回EOF。
随后的读操作将会返回c.
如果有多个字符被压回,则它们会以相反的次序被读出,
也就是说,最后被压入的字符第一个返回。
POSIX规定,只能确保一个字符的压回是正确的,并且其间不能有读操作。
有些系统只允许一个字符被压回,Linux 没有对这个数量进行约束,
你其至可以把所有的空间都用上。当然只压回一个字符肯定是成功的。


在调用ungetc()之后,如果你没有进行读操作就进行了文件位置操作(参见本章后面定位文件小节),
可能会导致压回的字符丢失。
这种情况发生在同一进程的多个线程之间,因为它们共享同一个缓冲区。


读入一行

函数fgets()从给定的流中读入一个字符串。
#include <stdio.h>

char * fgets (char *str, int size, FILE *stream);

从stream中最多读取size-1个字符到字符串str中。
该读操作完成时,一个null({post.abstract})会写入到str中。
一旦遇到EOF或换行符,就结束读操作。如果读到换行符,那么就把\n存到str中。
调用成功,返回str;失败则返回NULL。

68 | Chapter 3: Buffered I/O

----------------------------------


例如:
char buf[LINE_MAX];

if (!fgets (buf, LINE_MAX, stream))
/* error */

POSIX 在头文件limits.h中定入了LINE_MAX:
这是POSIX行处理接口可以操作的最大值。
Linux 的C 库没有这样的限制,一行可以是任意大小,但是你没办法接触LINE_MAXR 的定义。
需要移植到其他平台的程序可以利用LINE_MAX来保证安全。
这个值在linux上设置的相对很大,因此linux特有的程序不需要担心一行的容量限制。

读二进制串


通常情况下,这种基于行的读操作fgets()是有益的。几乎常常,它也很烦人。
有时候,开发者想使用非回车的分隔符,而有些开发者甚至不想要分隔符。
很少有开发人员想把分隔符存入缓冲区。
回想起来,把换行符存在返回的缓冲区中很少是正确的决定。


用fgetc()来实现fgets()的功能是件很容易的事。
比如,下面的代码从stream读入n-1字节,然后存入str,并在末尾追加一个'{post.abstract}':
char *s;
int c;

s = str;
while (--n > 0 && (c = fgetc (stream)) != EOF)
*s++ = c;
*s = '{post.abstract}';


这段代码可以扩展成读入到由d指定的分隔符后停止,在这个例子中d不能为空字符:

char *s;
int c = 0;


s = str;
while (--n > 0 && (c = fgetc (stream)) != EOF && (*s++ = c) != d)
;


if (c == d)
*--s = '{post.abstract}';
else
*s = '{post.abstract}';


如果将d设为'\n',那么这段代码跟fgets()的行为很相似了,只是前者将换行存入了缓冲区。

Reading from a Stream | 69

-----------------------------------

比起fgets()的实现,这个变种可能会慢一些,因为它反复地调用fgetc().
然而,这种情况跟之前我们说的dd那个例子是不同的。
虽然这段代码要承担额外的函数调用开销,它不承担系统调用开销,
也没有bs=1时,dd例子中未对齐的I/O负担。后者则是更大的问题。

读二进制数据

仅仅一次读入一个字符或一行对有些程序来说是不够的。
有时,开发者需要对复杂的二进制数据进行读写,比如C中的结构。
为此,标准I/O提供了fread():

#include <stdio.h>

size_t fread (void *buf, size_t size, size_t nr, FILE *stream);

调用fread()会从流stream中最多读入 nr 个元素,每个元素 size个字节,然后将它们存入buf指向的缓冲区中。
同时,文件指针会向前移动刚才读入的字节数量。

函数返回值是读入元素的个数(而不是字节数)。 如果返值小于nr,则表明出错或文件结束,
除非调用ferror()和feof()(见后面“错误及文件结束”),否则无法分辨这两种情况。

由于不同的变量大小,对齐,填充,和字节顺序,由一个程序写入的二进制数据对另一个程序是不可读的,
甚至同一个程序在不同机器上也会出现这种情况。

fread()最简单的例子是给定的流stream中读入一个线性的字符串:

char buf[64];
size_t nr;


nr = fread (buf, sizeof(buf), 1, stream);

if (nr == 0)

/* error */

等我们学到与fread()相对的函数fwrite()时再看一些复杂点的例子。

往流中写数据

和读操作一样,标准C语言库定义了许多函数对打开的流文件进行写操作。
本节将关注三个最常用的写操作:写一个单独的字符,写一个字符串和写二进制数据。
这些不同的写操作适合于带缓冲的I/O.
要想往一个流中写数据,这个流必须以适当的模式打开,也就是说除了 r 之外的其他模式。


70 | Chapter 3: Buffered I/O
----------------------------------
对齐问题


所有机器的架构都有数据对齐的要求。
程序员倾向于认为内存只是一个字节数组。
但是,处理器不会从内存中读和写字节大小的块,而是以特定的粒度大小来存取内存,
如2,4,8或16字节。
因为每一个进程的地址空间开始于地址0 ,进程必须从这个粒度大小的整数倍来开始存取数据。


因此,对C语言中的变量存储和读取时必须保持地址对齐。
一般情况下,变量会自然对齐,其中提到的调整的大小对应于C数据类型。
比如,一个32位的整数是以4个字节对齐的,换句话说就是,
int 应该被存储在能被4整除的内存地址上。


对未对准的数据进行访问会产生各种处罚,这些处罚取决于机器架构。
某些处理器可以访问错位的数据,但有大量性能损失。
某些处理器根本不能能这种数据进行访问,任何这样的意图都会引起硬件异常。
更严重的是,有些进程会悄无声息地丢弃低价位,这几乎可以完全肯定会导致意想不到的结果。


通常情况下,编译器会自动地对齐数据,这种对齐对程序员来说是透明的。
处理结构,手动管理内存的执行,将二进制数存入磁盘以及网络通信都会引起对齐的问题。
因此系统程序员应该精通这些问题。

第8章会更加深入地阐述对齐的问题


写一个单独的字符


和函数fgetc()的对应的是fputc():
#include <stdio.h>

int fputc (int c, FILE *stream);


fputc()函数将c指定的字符(强转为unsigned char)写入stream指向的流。
函数执行成功时返回c,否则返回EOF并设置相应的errno.
Use is simple:
使用很简单:
if (fputc ('p', stream) == EOF)
/* error */



该例子将字符p写入流stream,且stream必须是以可写模式打开的。
Writing to a Stream | 71

----------------------------------
写一个字符串

函数fputs()将一整串字符写入流stream中。
#include <stdio.h>

int fputs (const char *str, FILE *stream);


调用fputs()会将str指向的字符串里所有非分隔符之前的内容写入流stream。
成功时fputs()返回一个非负数,否则返回EOF.


下面的例子以追加模式打开一个文件,将给定的字符串写入流stream,然后关闭stream.

FILE *stream;

stream = fopen ("journal.txt", "a");
if (!stream)
/* error */


if (fputs ("The ship is made of wood.\n", stream) == EOF)
/* error */


if (fclose (stream) == EOF)
/* error */



写二进制数据
Individual characters and lines will not cut it when programs need to write complex
data. To directly store binary data such as C variables, standard I/O provides fwrite():
cut it????
标准I/O库提供了函数fwrite()用来直接存储二进制数据,比如C的变量。

#include <stdio.h>

size_t fwrite (void *buf,
size_t size,
size_t nr,
FILE *stream);


调用fwrite()会将buf指向的数据中最多nr个元素写入stream中,每个元素长度为size个字节。
文件指针将向前移动写入的字节数量。


返回值是成功写入的元素个数(而不是字节数)。
返回值小于nr标志着出错了。


带缓冲机制I/O的示例程序


现在我们看一个例子,一个完整的程序,它整合了我们迄今讲到的许多接口。
程序首先定义了结构pirate,然后用它声明了两个变量实例。
程序初始结了其中一个变量,然后通过一个输入出流把它写入磁盘文件中。


72 | Chapter 3: Buffered I/O


通过另一个不同的流,程序将数据读入到另一个结构pirate实例中。
最后,程序打印出结构的内容。

#include <stdio.h>
int main (void)
{
FILE *in, *out;
struct pirate {
char name[100]; /* real name */
unsigned long booty; /* in pounds sterling */
unsigned int beard_len; /* in inches */

} p, blackbeard = { "Edward Teach", 950, 48 };

out = fopen ("data", "w");

if (!out) {
perror ("fopen");
return 1;

}

if (!fwrite (&blackbeard, sizeof (struct pirate), 1, out)) {
perror ("fwrite");
return 1;

}

if (fclose (out)) {
perror ("fclose");
return 1;

}

in = fopen ("data", "r");

if (!in) {
perror ("fopen");
return 1;

}

if (!fread (&p, sizeof (struct pirate), 1, in)) {
perror ("fread");
return 1;

}

if (fclose (in)) {
perror ("fclose");
return 1;

}

printf ("name=\"%s\" booty=%lu beard_len=%u\n",
p.name, p.booty, p.beard_len);

return 0;
}


输出结果当然是原始的数据:

name="Edward Teach" booty=950 beard_len=48

Sample Program Using Buffered I/O | 73

----------------------------------

再次强调,有一点要引起注意的是,由于不同变量的大小,对齐等问题,
由一个程序写入的二进制数据对另一个程序来说可能是不可读的。
也就是说,不同的程序或者同一程序在不同的机器上也许不能正确读出由fwrite()写入的数据。
上面的程序中,unsigned long 的大小可能会有变化,或者填充字节数不同,这些都是要考虑的差异。
只有特定机器上的特定ABI才能保障这些数据都是恒定的。


定位一个流

一般情况下,操纵流指针的当前位置是很有用的。
比如一个应用程序可能正在读一个复杂的基于记录的文件,因此需要不断地跳来跳去。
或者有可能程序需要将文件指针移到文件开头。
不管哪种情况,标准I/O提供了一组接口,其功能等同于系统调用lseek()(见第2章);
这些接口中,最常用的是fseek()函数,它有两个参数:offset和whence.


#include <stdio.h>
int fseek (FILE *stream, long offset, int whence);

调用该函数时,如果whence为SEEK_SET,那么文件指针更新为offset的值;
如果whence为SEEK_CUR,那么文件指针更新为当前位置加上offset的值;
如果whence为SEEK_END,那么文件指针更新为文件未尾加上offset的值。

如果调用成功,fseek()返回0,清除EOF标记,并且使ungetc()失效(如果有的话)。
错误时返回-1,并设置相就的出错位。
最常见的错误信息是非法流(EBADF)和非法的whence参数。

作为选择,标准I/O提供了函数fsetpos():

#include <stdio.h>

int fsetpos (FILE *stream, fpos_t *pos);

该函数将流stream的当前位置设置为pos.
它等价于参数whence为SEEK_SET时调用函数fseek().
调用成功返回0;否则返回-1,并设置相应的出错位。
这个函数(连同其对应的fgetpos(),后面会讲到)是专门针对其他(非UNIX)平台的,这些平台具有复杂的类型来表示流位置。
在这些平台上,该函数是来以一个任意值来设置流位置的唯一途径,因为C语言的 long 大概是不够的。
linux特色的程序没必要使用这个接口,当然如果想要跨平台支持,也可以利用该函数。

标准I/O还提供了一条捷径,rewind():

#include <stdio.h>

void rewind (FILE *stream);

74 | Chapter 3: Buffered I/O


这样调用:
rewind (stream);

将文件位置重置到流的开始。它等价于:
fseek (stream, 0, SEEK_SET);

不同的是前者清除了出错标记。

请注意,rewind()没有返回值,所以不能直接跟判断出误条件打交道。
调用者如果想确认是否出错,则应该在调用之前清除出错标记errno,并在调用之后检查变量errno是否为0.
例如:

errno = 0;

rewind (stream);

if (errno)

/* error */

获取当前流的位置

与lseek()不同,fseek()并不返回更新后的文件位置。
ftell()作为一个单独的接口来实现这个目的,该函数返回文件的当前位置。
#include <stdio.h>

long ftell (FILE *stream);

出错时返回-1,并设置相应的出错标记。
作为选择,标准I/O还提供了fgetpos():

#include <stdioh.h>

int fgetpos (FILE *stream, fpos_t *pos);

调用成功,fgetpos()返回0,并将当前文件位置设置为pos.
失败则返回-1,并设置相应的出错标记。
同fsetpos()一样,fgetpos()是专门为具有复杂文件位置类型的非linux平台提供的。

清除流

标准I/O库提供了一个函数用来将用户缓冲区里的内容写入内核,以确保所有的数据都通过write()写入流中。
这个函数就是fflush():
#include <stdio.h>

int fflush (FILE *stream);

Flushing a Stream | 75

----------------------------------

调用该函数,所有stream指向的流中所有未写的数据均被写入内核。
如果参数stream为NULL,那么进程中所有打开的输入流都会被清除。
调用成功时fflush()返回0,否则返回EOF,并设置相应有出错位。

要想理解fflush()的影响,我们必须明白C库的缓冲区与内核自己的缓冲区之间的区别。
本章所描述的所有函数都作用在驻留在用户空间的由C库维护的缓冲区中,而不是内核缓冲区。
这就是性能优化所在,程序是在用户空间,因此运行的是用户区代码,而不涉及系统调用。
只有在需要访问磁盘或其介质时才会进行系统调用。


fflush()仅仅只是将用户缓冲区的数据写入内核缓冲区。
其效果等同于不使用用户态缓冲区而直接调用write()函数。
但是它不保证这些数据会被物理地写入介质,要完成这个功能可以调用类似fsync()函数(见第二章“同步I/O”)。
最有可能的情况是,你会先调用fflush(),紧接着调用fsync():
这样的话,首先可以确保用户态缓冲区内容都写入内核缓冲区中, 然后再保障内核缓冲的数据被写入磁盘。

出错处理及文件结束(EOF)

一些标准I/O接口,如fread(),与调用者的侦错交流很差,因为它们没有提供任何机制去辨别一般出错还是文件结束。
对于这些函数以及其他的一些情况,检查给定流的状态以确定是否出错或到达文件结束是很有用的。
标准I / O提供了两个接口来达到这一目的。
函数ferror()就是用来测试流上是否有出错标记的。
include <stdio.h>

int ferror (FILE *stream);

出错标记是由其他标准I/O接口为了响影出错情况而设置的。
如果出错标记被设置,函数返为一个非零值,否则返回。

函数feof()测试stream上是否有EOF标记。
include <stdio.h>

int feof (FILE *stream);

EOF标记是由其他标准函数为了响文件结束而设置的。
如果该标记被设置,函数返回非0值,否则返回0.
clearerr()函数用来清除stream的出错和EOF标记。
#include <stdio.h>

void clearerr (FILE *stream);

76 | Chapter 3: Buffered I/O

---------------------------------

该函数没有返回值并且不会失败(没有办法知道实参stream是否合法)。
clearerr()只应该在检查错误和EOF标记之后调用,因为它们会被不可挽回地丢弃。
比如:

/* 'f' 是一个合法的流 */

if (ferror (f))
printf ("Error on f!\n");


if (feof (f))
printf ("EOF on f!\n");


clearerr (f);

获取相应的文件描述符

有时,获取支持给定流的文件描述符是有利的。
比如,当没有相应的标准I/O函数时,通过文件描述符进行系统调用是很有用的。
fileno()用来获取支持流的文件描述符:

#include <stdio.h>

int fileno (FILE *stream);

调用成功时fileno()返回与stream相对应的文件描述符。
失败时返回-1,这只能发生在当实参stream非法的情况,此时函数置出错标记EBADF.

通常不建议混合地使用标准I/O函数与系统调用。
程序员必须谨慎使用fileno()以确保适当的行为。


操控缓冲区

标准I/O实现了三种类型的缓冲区,并且为开发者提供了一个接口来操作缓冲类型及缓冲区大小.
不同类型的用户缓冲区服务于不同的目的,并且分别适合不同的情况.下面是这些选择:

无缓冲

不进行任何用户态缓冲,数据直接提交给内核处理.
这是用户态缓冲的对立面,因此此选项是不常用的.
默认情况下,标准错误(stderr)属于此类型.

Controlling the Buffering | 77


行缓冲

缓冲是以每一行为基础的.
每个换行符将使缓冲提交给内核.
行缓冲对于向屏幕输出的流是有意义的.
因此,这是终端的却省缓冲(标准输出stdout默认是行缓冲的).

块缓冲

缓冲是以块为单位进行的.
这就是我们在本章开头提到的缓冲类型,它对文件操作来说是最理想的选择.
所有与文件相关的流都是块缓冲的.
标准I/O对此使用的术语是全缓冲.

在大多数情况下,默认的缓冲类型是正确的和最佳的。但是,标准I/O也确实提供了一个接口来控制所用缓冲的类型:
#include <stdio.h>

int setvbuf (FILE *stream, char *buf, int mode, size_t size);

setvbuf()函数将流stream的缓冲类型设置为模式mode,可选模式有:
_IONBF
无缓冲

_IOLBF
行缓冲

_IOFBF
块缓冲

模式为_IONBF时,buf和size的值被忽略,其他模式下,buf可以指向一个大小为size的缓冲区,标准I/O会将它用作流stream的缓冲区.
如果buf为NULL,glibc会自动为其分配一个缓冲区.

必须在打开流后,并且所有对流的其他操作被调用之前,才能调用setvbuf().
成功,返回0,否则返回一个非0值.

如果人为地提供了缓冲区,那么它必须在流关闭之前一直存在.
一个常见的错误是在一个作用域里声明一个缓冲,但是这个作用域比流更早地结束了.
特别地,注意不要在main()里提供一个局部缓冲区,然后却没有明确地关闭流.
比如,下面是一个错误的例子:


#include <stdio.h>

int main (void)
{
char buf[BUFSIZ];

/* set stdin to block-buffered with a BUFSIZ buffer */
setvbuf (stdout, buf, _IOFBF, BUFSIZ);

78 | Chapter 3: Buffered I/O


printf ("Arrr!\n");

return 0;
}

---------------------------------

可以这样修复这个错误:在退出作用域之前显式地关闭流,或者将buf设为全局变量.

一般来说,开发人员没有必要参与流上的缓冲区.
除了stderr外,终端是行缓冲的才有意义.
文件是块缓冲的才有意义.
默认的缓冲区大小是BUFSIZ,它的定义在<stdio.h>,通常情况下这个值(一个典型块大小的很多倍)是最优的选择.

线程安全

一簇线程共同运行在同一进程的空间中.
和它等同的概念是多相进程共享同一地地空间.
线程可以运行在任何时间,而且可以覆盖共享数据,只要注意同步地访问数据,或者使数据成为线程局部所有的.
支持线程的操作系统都提供了锁机制(编程结构,以保证线程之间相斥)来确保线程不会改写其他线程的数据.
标准I/O使用这些机制,仅有这些当然是不够的.
比如,有时你会想要锁住一组函数调用,增大临界区(不被其他线程干涉的大块代码)的作用范围.
而在另一些情况下,你可能希望完全取消锁机制来提高效率.
在本节中,我们会分别讨论这两种情况的实现.


标准I/O函数天生就是线程安全的.
在内部,这些函数联合了一把锁,一个锁计数器,并且它们被每个流的其中一个线程拥有.
任何指定的线程必须获取了锁才能进行I/O请求.
同一个流上的不同线程不能进行交错地进行标准I/O操作,
因此,在单一的函数调用范围内,标准I/O操作是原子操作.


当然在实践中许多应用中需要比单独的函数调用更大意义上的原子操作.
比如,如果多个线程都有写请求,虽然个别写并不会交错,也导致乱码输出,
但也许程序想要每个写操作不被打断,一次性完成.
为此,标准I/O提供了一组函数用来单独地操控与流相关的锁.

通常情况下,消除锁将导致各种各样的问题.
但是一些程序可能会明确地将所有的I/O操作都委托给单独一个线程.
在那种情况下,就没必要锁的开销.


Thread Safety | 79

手动文件锁

调用函数flockfile()时,线程会堵塞直到流没有被锁上,
然后获得锁,增加锁计数器,成为拥有锁的线程,最后返回:
#include <stdio.h>
void flockfile (FILE *stream);

函数funlockfile()减少流相关联的锁计数器:
#include <stdio.h>
void funlockfile (FILE *stream);

如果锁计数器达到零时,当前线程放弃流的所有权,
另一个线程现在可以获得这个锁.


这些函数嵌套调用.也就是说,一个单独的线程可以多次调用flockfile(),
并且流不会被解锁除非该进程调用了同样次数的funlockfile().

ftrylockfile()是flockfile()的一个非阻塞版本.
#include <stdio.h>

int ftrylockfile (FILE *stream);

如果流目前被锁定,则ftrylockfile()什么都不做立即返回一个非0值.
如果流目前没有被锁定,当前线程获得锁,增加锁计数器,成为拥有锁的线程,并且返回0.
Let’s consider an example:
我们看一个例子:
flockfile (stream);

fputs ("List of treasure:\n", stream);
fputs (" (1) 500 gold coins\n", stream);
fputs (" (2) Wonderfully ornate dishware\n", stream);

funlockfile (stream);

虽然单独的fputs()操作永远不会产生竞争,比如我们不可能打断"List of treasure",
但是如果来自别的线程中的标准I/O操作也对同一个流进行访问,则有可能打断连续的两个fputs().
理想的情况下,一个应用中多个线程不会访问同一个流.
但是,如果你的程序确实有这种需求的话,你需要一个比单独调用函数更大范围的原子操作
那么flockfile()家族可以帮你扭转败局.
80 | Chapter 3: Buffered I/O

-----------------

为流解锁

还有第二个原因进行手动锁流.
随着对锁的控制粒度更加细化和精确化,而这些操作只能有程序员进行,
有可能需要尽量减少锁的开销来提高性能.
为此,Linux 提供了另外一组函数,它们就像普通标准I/O接口的姊妹组,
他们不进行任何锁操作,实际上他们是标准I/O对应的非加锁版本.


#define _GNU_SOURCE

#include <stdio.h>

int fgetc_unlocked (FILE *stream);

char *fgets_unlocked (char *str, int size, FILE *stream);

size_t fread_unlocked (void *buf, size_t size, size_t nr,

FILE *stream);

int fputc_unlocked (int c, FILE *stream);

int fputs_unlocked (const char *str, FILE *stream);

size_t fwrite_unlocked (void *buf, size_t size, size_t nr,

FILE *stream);

int fflush_unlocked (FILE *stream);

int feof_unlocked (FILE *stream);

int ferror_unlocked (FILE *stream);

int fileno_unlocked (FILE *stream);

void clearerr_unlocked (FILE *stream);

这些函数的功能和对应带锁机制的姊妹函数相同,只是前者不会检查或获取指定流上的锁.
程序员有责任确保在需要的时候,锁能被正确地手动获得和释放.


虽然POSIX确实定义了一些标准I/O函数的非带锁版本,但是上面的函数一个也不在POSIX范围内.
它们都是Linux特色的,尽管其他Unix的变种支持其中的一部分.

评价标准I/O

正如被广泛应用一样,标准I/O也广泛地被专家挑出缺陷.
有些函数如fgets()的功能是不够的.
有些函数如gets()是如此可怕以致于快被逐出标准库了.


影响标准I/O性能的头号杀手是双复本.
读数据时,标准I/O发起一个系统调用read()到内核,将数据从内核拷到标准I/O缓冲区.
然后当应用程序通过标准I/O发起一个读请求,比如fgetc(),那么数据会被第二次被拷贝,
这次是从标准I/O的缓冲区拷贝到应用程序提供的缓冲区.
写操作以相反的方式工作:一次是将数据从程序缓冲区拷贝到标准I/O的缓冲区,
然后又被函数write()拷贝到内核.

Critiques of Standard I/O | 81

一个预防双复本实现方法是,每次读请求都返回一个指向标准I/O缓冲区的一个指针.
那么数据就可以直接被从标准I/O缓冲区里读取,不必再进行一次额外的拷贝.
如果确实需要将数据写入程序内部自己的缓冲区中,比如要对它进行更新,那么总是可以进行手动拷贝.
这个实现过程可以提供一个"免费"的接口:当应用程序结束了对给定读缓冲区的操作时,允许其向外发信号.


写操作可能会麻烦一点,但是仍然可以避免双副本.
当发起写请求时,记录下指针.
最后,当要刷新缓冲区数据到内核时,可以遍历所记录的指针,由此将数据写出.
这可以使用分散-收集的I/O,只需要一个系统调用writev()。
(我们将在接下来的一章中讨论到分散-收集的I/O.)


C库中存在高度优化的用户缓冲机制,它解决双副本的方法跟我们刚才讨论的很相似.
另外,一些开发者选择去实现自己的用户缓冲方案.
尽管有这些代替品,标准I/O依然很受欢迎.

总结

标准I/O是由标准C库提供的一个用户态缓冲库.
除去一点小的缺陷,它是一个强大的,非常受欢迎的解决方案。
许多C程序员,事实上,只知道标准的I/O.
当然,对终端I/O来说,基于行的缓冲是理想的,这只能标准I/O来实现.
谁会直接调用write()来打印数据到标准输出?


通常情况下,标准I/O及用户态缓冲区在处理下面情况时才有意义:

. 你可能会频繁进行系统调用,并且你想要通过合并系统调用来尽量减少开销.

. 性能是至关重要的,并且你想要确保所有的I/O操作都是以块大小的整数倍为单位,还要保证块对齐.

. 你的访问模式是以字符或行为基础的,你想要一些函数来满足这种要求,并且不通过不相干的系统调用.

. 比起低级别的Linux系统调用,你更喜欢高级别的接口.

然而,最大的灵活性还是存在于当你直接跟linux系统函数打交道的时候.
下一章中,我们将学习高级形式的I/O以及对应的系统调用.


 
immicf @ 2009-04-09 16:13

gcc and g++分别是gnu的c & c++编译器

gcc/g++在执行编译工作的时候,总共需要4步

1.预处理,生成.i的文件[预处理器cpp]
2.将预处理后的文件不转换成汇编语言,生成文件.s[编译器egcs]
3.有汇编变为目标代码(机器代码)生成.o的文件[汇编器as]
4.连接目标代码,生成可执行程序[链接器ld]

[参数详解]
-x language filename
设定文件所使用的语言,使后缀名无效,对以后的多个有效.也就是根
据约定C语言的后缀名称是.c的,而C++的后缀名是.C或者.cpp,如果
你很个性,决定你的C代码文件的后缀名是.pig 哈哈,那你就要用这
个参数,这个参数对他后面的文件名都起作用,除非到了下一个参数
的使用。
可以使用的参数吗有下面的这些
`c', `objective-c', `c-header', `c++', `cpp-output',
`assembler', and `assembler-with-cpp'.
看到英文,应该可以理解的。
例子用法:
gcc -x c hello.pig

-x none filename
关掉上一个选项,也就是让gcc根据文件名后缀,自动识别文件类型
例子用法:
gcc -x c hello.pig -x none hello2.c

-c
只激活预处理,编译,和汇编,也就是他只把程序做成obj文件
例子用法:
gcc -c hello.c
他将生成.o的obj文件

-S
只激活预处理和编译,就是指把文件编译成为汇编代码。
例子用法
gcc -S hello.c
他将生成.s的汇编代码,你可以用文本编辑器察看

-E
只激活预处理,这个不生成文件,你需要把它重定向到一个输出文件里
面.
例子用法:
gcc -E hello.c > pianoapan.txt
gcc -E hello.c | more
慢慢看吧,一个hello word 也要与处理成800行的代码

-o
制定目标名称,缺省的时候,gcc 编译出来的文件是a.out,很难听,如果
你和我有同感,改掉它,哈哈
例子用法
gcc -o hello.exe hello.c (哦,windows用习惯了)
gcc -o hello.asm -S hello.c

-pipe
使用管道代替编译中临时文件,在使用非gnu汇编工具的时候,可能有些问

gcc -pipe -o hello.exe hello.c

-ansi
关闭gnu c中与ansi c不兼容的特性,激活ansi c的专有特性(包括禁止一
些asm inline typeof关键字,以及UNIX,vax等预处理宏,

-fno-asm
此选项实现ansi选项的功能的一部分,它禁止将asm,inline和typeof用作
关键字。

-fno-strict-prototype
只对g++起作用,使用这个选项,g++将对不带参数的函数,都认为是没有显式
的对参数的个数和类型说明,而不是没有参数.
而gcc无论是否使用这个参数,都将对没有带参数的函数,认为城没有显式说
明的类型

-fthis-is-varialble
就是向传统c++看齐,可以使用this当一般变量使用.

-fcond-mismatch
允许条件表达式的第二和第三参数类型不匹配,表达式的值将为void类型

-funsigned-char
-fno-signed-char
-fsigned-char
-fno-unsigned-char
这四个参数是对char类型进行设置,决定将char类型设置成unsigned char(前
两个参数)或者 signed char(后两个参数)

-include file
包含某个代码,简单来说,就是便以某个文件,需要另一个文件的时候,就可以
用它设定,功能就相当于在代码中使用#include<filename>
例子用法:
gcc hello.c -include /root/pianopan.h

-imacros file
将file文件的宏,扩展到gcc/g++的输入文件,宏定义本身并不出现在输入文件


-Dmacro
相当于C语言中的#define macro

-Dmacro=defn
相当于C语言中的#define macro=defn

-Umacro
相当于C语言中的#undef macro

-undef
取消对任何非标准宏的定义

-Idir
在你是用#include"file"的时候,gcc/g++会先在当前目录查找你所制定的头
文件,如果没有找到,他回到缺省的头文件目录找,如果使用-I制定了目录,他
回先在你所制定的目录查找,然后再按常规的顺序去找.
对于#include<file>,gcc/g++会到-I制定的目录查找,查找不到,然后将到系
统的缺省的头文件目录查找

-I-
就是取消前一个参数的功能,所以一般在-Idir之后使用

-idirafter dir
在-I的目录里面查找失败,讲到这个目录里面查找.

-iprefix prefix
-iwithprefix dir
一般一起使用,当-I的目录查找失败,会到prefix+dir下查找

-nostdinc
使编译器不再系统缺省的头文件目录里面找头文件,一般和-I联合使用,明确
限定头文件的位置

-nostdin C++
规定不在g++指定的标准路经中搜索,但仍在其他路径中搜索,.此选项在创建
libg++库使用

-C
在预处理的时候,不删除注释信息,一般和-E使用,有时候分析程序,用这个很
方便的

-M
生成文件关联的信息。包含目标文件所依赖的所有源代码
你可以用gcc -M hello.c来测试一下,很简单。

-MM
和上面的那个一样,但是它将忽略由#include<file>造成的依赖关系。

-MD
和-M相同,但是输出将导入到.d的文件里面

-MMD
和-MM相同,但是输出将导入到.d的文件里面

-Wa,option
此选项传递option给汇编程序;如果option中间有逗号,就将option分成多个选
项,然后传递给会汇编程序

-Wl.option
此选项传递option给连接程序;如果option中间有逗号,就将option分成多个选
项,然后传递给会连接程序.

-llibrary
制定编译的时候使用的库
例子用法
gcc -lcurses hello.c
使用ncurses库编译程序

-Ldir
制定编译的时候,搜索库的路径。比如你自己的库,可以用它制定目录,不然
编译器将只在标准库的目录找。这个dir就是目录的名称。

-O0
-O1
-O2
-O3
编译器的优化选项的4个级别,-O0表示没有优化,-O1为缺省值,-O3优化级别最
高  

-g
只是编译器,在编译的时候,产生条是信息。

-gstabs
此选项以stabs格式声称调试信息,但是不包括gdb调试信息.

-gstabs+
此选项以stabs格式声称调试信息,并且包含仅供gdb使用的额外调试信息.

-ggdb
此选项将尽可能的生成gdb的可以使用的调试信息.
-static
此选项将禁止使用动态库,所以,编译出来的东西,一般都很大,也不需要什么
动态连接库,就可以运行.
-share
此选项将尽量使用动态库,所以生成文件比较小,但是需要系统由动态库.
-traditional
试图让编译器支持传统的C语言特性


GNU 的调试器称为 gdb,该程序是一个交互式工具,工作在字符模式。在 X Window 系统中,有一个 gdb 的
前端图形工具,称为 xxgdb。gdb 是功能强大的调试程序,可完成如下的调试任务:
* 设置断点;
* 监视程序变量的值;
* 程序的单步执行;
* 修改变量的值。
在可以使用 gdb 调试程序之前,必须使用 -g 选项编译源文件。可在 makefile 中如下定义 CFLAGS 变量:
CFLAGS = -g
运行 gdb 调试程序时通常使用如下的命令:
gdb progname

在 gdb 提示符处键入help,将列出命令的分类,主要的分类有:
* aliases:命令别名
* breakpoints:断点定义;
* data:数据查看;
* files:指定并查看文件;
* internals:维护命令;
* running:程序执行;
* stack:调用栈查看;
* statu:状态查看;
* tracepoints:跟踪程序执行。
键入 help 后跟命令的分类名,可获得该类命令的详细清单。


#DENO#
gdb 的常用命令
表 1-4 常用的 gdb 命令
命令 解释
break NUM 在指定的行上设置断点。
bt 显示所有的调用栈帧。该命令可用来显示函数的调用顺序。
clear 删除设置在特定源文件、特定行上的断点。其用法为:clear FILENAME:NUM。
continue 继续执行正在调试的程序。该命令用在程序由于处理信号或断点而
导致停止运行时。
display EXPR 每次程序停止后显示表达式的值。表达式由程序定义的变量组成。
file FILE 装载指定的可执行文件进行调试。
help NAME 显示指定命令的帮助信息。
info break 显示当前断点清单,包括到达断点处的次数等。
info files 显示被调试文件的详细信息。
info func 显示所有的函数名称。
info local 显示当函数中的局部变量信息。
info prog 显示被调试程序的执行状态。
info var 显示所有的全局和静态变量名称。
kill 终止正被调试的程序。
list 显示源代码段。
make 在不退出 gdb 的情况下运行 make 工具。
next 在不单步执行进入其他函数的情况下,向前执行一行源代码。
print EXPR 显示表达式 EXPR 的值。


1.8.5 gdb 使用范例
-----------------
清单 一个有错误的 C 源程序 bugging.c
-----------------
#include
#include

static char buff [256];
static char* string;
int main ()
{

printf ("Please input a string: ");
gets (string);

printf ("\nYour string is: %s\n", string);
}
-----------------
上面这个程序非常简单,其目的是接受用户的输入,然后将用户的输入打印出来。该程序使用了一个未经过初
始化的字符串地址 string,因此,编译并运行之后,将出现 Segment Fault 错误:
$ gcc -o test -g test.c
$ ./test
Please input a string: asfd
Segmentation fault (core dumped)
为了查找该程序中出现的问题,我们利用 gdb,并按如下的步骤进行:
1.运行 gdb bugging 命令,装入 bugging 可执行文件;
2.执行装入的 bugging 命令;
3.使用 where 命令查看程序出错的地方;
4.利用 list 命令查看调用 gets 函数附近的代码;
5.唯一能够导致 gets 函数出错的因素就是变量 string。用 print 命令查看 string 的值;
6.在 gdb 中,我们可以直接修改变量的值,只要将 string 取一个合法的指针值就可以了,为此,我们在第
11 行处设置断点;
7.程序重新运行到第 11 行处停止,这时,我们可以用 set variable 命令修改 string 的取值;
8.然后继续运行,将看到正确的程序运行结果。


 
immicf @ 2009-04-09 16:11

1。gcc包含的c/c++编译器
gcc,cc,c++,g++,gcc和cc是一样的,c++和g++是一样的,(没有看太明白前面这半句是什
么意思:))一般c程序就用gcc编译,c++程序就用g++编译

2。gcc的基本用法
gcc test.c这样将编译出一个名为a.out的程序
gcc test.c -o test这样将编译出一个名为test的程序,-o参数用来指定生成程序的名


3。为什么会出现undefined reference to 'xxxxx'错误?
首先这是链接错误,不是编译错误,也就是说如果只有这个错误,说明你的程序源码本
身没有问题,是你用编译器编译时参数用得不对,你没

有指定链接程序要用到得库,比如你的程序里用到了一些数学函数,那么你就要在编译
参数里指定程序要链接数学库,方法是在编译命令行里加入-lm。

4。-l参数和-L参数
-l参数就是用来指定程序要链接的库,-l参数紧接着就是库名,那么库名跟真正的库文
件名有什么关系呢?
就拿数学库来说,他的库名是m,他的库文件名是libm.so,很容易看出,把库文件名的
头lib和尾.so去掉就是库名了。

好了现在我们知道怎么得到库名了,比如我们自已要用到一个第三方提供的库名字叫lib
test.so,那么我们只要把libtest.so拷贝到/usr/lib

里,编译时加上-ltest参数,我们就能用上libtest.so库了(当然要用libtest.so库里
的函数,我们还需要与libtest.so配套的头文件)。

放在/lib和/usr/lib和/usr/local/lib里的库直接用-l参数就能链接了,但如果库文件
没放在这三个目录里,而是放在其他目录里,这时我们

只用-l参数的话,链接还是会出错,出错信息大概是:“/usr/bin/ld: cannot find
-lxxx”,也就是链接程序ld在那3个目录里找不到

libxxx.so,这时另外一个参数-L就派上用场了,比如常用的X11的库,它放在/usr/X11R
6/lib目录下,我们编译时就要用-L/usr/X11R6/lib -

lX11参数,-L参数跟着的是库文件所在的目录名。再比如我们把libtest.so放在/aaa/bb
b/ccc目录下,那链接参数就是-L/aaa/bbb/ccc -ltest

另外,大部分libxxxx.so只是一个链接,以RH9为例,比如libm.so它链接到/lib/libm.s
o.x,/lib/libm.so.6又链接到/lib/libm-2.3.2.so,

如果没有这样的链接,还是会出错,因为ld只会找libxxxx.so,所以如果你要用到xxxx
库,而只有libxxxx.so.x或者libxxxx-x.x.x.so,做一

个链接就可以了ln -s libxxxx-x.x.x.so libxxxx.so

手工来写链接参数总是很麻烦的,还好很多库开发包提供了生成链接参数的程序,名字
一般叫xxxx-config,一般放在/usr/bin目录下,比如

gtk1.2的链接参数生成程序是gtk-config,执行gtk-config --libs就能得到以下输出"-
L/usr/lib -L/usr/X11R6/lib -lgtk -lgdk -rdynamic

-lgmodule -lglib -ldl -lXi -lXext -lX11 -lm",这就是编译一个gtk1.2程序所需的g
tk链接参数,xxx-config除了--libs参数外还有一个参

数是--cflags用来生成头文
件包含目录的,也就是-I参数,在下面我们将会讲到。你可以试试执行gtk-config
--libs --cflags,看看输出结果。
现在的问题就是怎样用这些输出结果了,最笨的方法就是复制粘贴或者照抄,聪明的办
法是在编译命令行里加入这个`xxxx-config --libs --

cflags`,比如编译一个gtk程序:gcc gtktest.c `gtk-config --libs --cflags`这样
就差
不多了。注意`不是单引号,而是1键左边那个键。

除了xxx-config以外,现在新的开发包一般都用pkg-config来生成链接参数,使用方法
跟xxx-config类似,但xxx-config是针对特定的开发包

,但pkg-config包含很多开发包的链接参数的生成,用pkg-config --list-all命令可以
列出所支持的所有开发包,pkg-config的用法就是pkg

-config pagName --libs --cflags,其中pagName是包名,是pkg-config--list-all里
列出名单中的一个,比如gtk1.2的名字就是gtk+,pkg-

config gtk+ --libs --cflags的作用跟gtk-config --libs --cflags是一样的。比如:
gcc gtktest.c `pkg-config gtk+ --libs --cflags`



5。-include和-I参数
-include用来包含头文件,但一般情况下包含头文件都在源码里用#include xxxxxx实现
,-include参数很少用。-I参数是用来指定头文件目录

,/usr/include目录一般是不用指定的,gcc知道去那里找,但是如果头文件不在/usr/i
nclude里我们就要用-I参数指定了,比如头文件放

在/myinclude目录里,那编译命令行就要加上-I/myinclude参数了,如果不加你会得到
一个"xxxx.h: No such file or directory"的错误。-I

参数可以用相对路径,比如头文件在当前目录,可以用-I.来指定。上面我们提到的--cf
lags参数就是用来生成-I参数的。

6。-O参数
这是一个程序优化参数,一般用-O2就是,用来优化程序用的,比如gcc test.c -O2,优
化得到的程序比没优化的要小,执行速度可能也有所提

高(我没有测试过)。

7。-shared参数
编译动态库时要用到,比如gcc -shared test.c -o libtest.so

8。几个相关的环境变量
PKG_CONFIG_PATH:用来指定pkg-config用到的pc文件的路径,默认是/usr/lib/pkgconf
ig,pc文件是文本文件,扩展名是.pc,里面定义开发

包的安装路径,Libs参数和Cflags参数等等。
CC:用来指定c编译器。
CXX:用来指定cxx编译器。
LIBS:跟上面的--libs作用差不多。
CFLAGS:跟上面的--cflags作用差不多。
CC,CXX,LIBS,CFLAGS手动编译时一般用不上,在做configure时有时用到,一般情况
下不用管。
环境变量设定方法:export ENV_NAME=xxxxxxxxxxxxxxxxx

9。关于交叉编译
交叉编译通俗地讲就是在一种平台上编译出能运行在体系结构不同的另一种平台上,比
如在我们地PC平台(X86 CPU)上编译出能运行在sparc

CPU平台上的程序,编译得到的程序在X86 CPU平台上是不能运行的,必须放到sparc
CPU平台上才能运行。
当然两个平台用的都是linux。

这种方法在异平台移植和嵌入式开发时用得非常普遍。

相对与交叉编译,我们平常做的编译就叫本地编译,也就是在当前平台编译,编译得到
的程序也是在本地执行。

用来编译这种程序的编译器就叫交叉编译器,相对来说,用来做本地编译的就叫本地编
译器,一般用的都是gcc,但这种gcc跟本地的gcc编译器

是不一样的,需要在编译gcc时用特定的configure参数才能得到支持交叉编译的gcc。

为了不跟本地编译器混淆,交叉编译器的名字一般都有前缀,比如sparc-xxxx-linux-gn
u-gcc,sparc-xxxx-linux-gnu-g++ 等等

10。交叉编译器的使用方法
使用方法跟本地的gcc差不多,但有一点特殊的是:必须用-L和-I参数指定编译器用spar
c系统的库和头文件,不能用本地(X86)
的库(头文件有时可以用本地的)。
例子:
sparc-xxxx-linux-gnu-gcc test.c -L/path/to/sparcLib -I/path/to/sparcInclude