Reading 'The Art of UNIX Programming'.

本文摘录了《UNIX编程艺术》一书中的核心原则与设计理念,涵盖了从模块化编程到透明性和多程序设计等关键主题。书中强调了简单性、清晰度及避免过度复杂的重要性,并探讨了多种编程实践和技术选择如何影响软件质量。

‘The Art of UNIX Programming'原版,人民邮电出版社 2006年8月第1版,本篇页码对照此版书籍

以下为阅读笔记,转载请注明出处

颜色说明:

黑色 -- Summary of the book

红色 -- Crob's comment

蓝色 -- Important summary

 

Chapter 1   Philosophy Matters

P13

More of the Unix philosophy was implied not by what these elders said
but by what they did and the example Unix itself set. Looking at the
whole, we can abstract the following ideas:

   1.Rule of Modularity: Write simple parts connected by clean interfaces.
   2.Rule of Clarity: Clarity is better than cleverness.
   3.Rule of Composition: Design programs to be connected to other programs.
   4.Rule of Separation: Separate policy from mechanism; separate interfaces from engines.
   5.Rule of Simplicity: Design for simplicity; add complexity only where you must.
   6.Rule of Parsimony: Write a big program only when it is clear by demonstration that nothing else will      7.Rule of Transparency: Design for visibility to make inspection and debugging easier.
   8.Rule of Robustness: Robustness is the child of transparency and simplicity.
   9.Rule of Representation: Fold knowledge into data so program logic can be stupid and robust.
  10.Rule of Least Surprise: In interface design, always do the least surprising thing.
  11.Rule of Silence: When a program has nothing surprising to say, it should say nothing.
  12.Rule of Repair: When you must fail, fail noisily and as soon as possible.
  13.Rule of Economy: Programmer time is expensive; conserve it in preference to machine time.
  14.Rule of Generation: Avoid hand-hacking; write programs to write programs when you can.
  15.Rule of Optimization: Prototype before polishing. Get it working before you optimize it.
  16.Rule of Diversity: Distrust all claims for “one true way”.
  17.Rule of Extensibility: Design for the future, because it will be here sooner than you think.

 

P14

Controlling complexity is the essense of computer programming.

 

P17

About excessive complexity comes from project requirements.......

Either way, everybody loses in the end.

The only way to avoid these traps is to encourage a software culture that knows that small is beautiful, that actively resists bloat and complexity: an engineering tradition that puts a high value on simple solutions, that looks for ways to break program systems up into small cooperatingpieces, and that reflexively fights attempts to gussy up programs with a lot of chrome (or even worse, to design programs around the chrome)

I think that's really a hard job to make chinese native customer knows 'the simple/small is beautiful'. But we have to do.  On the other hand, some pressure come from sales dept's requirements.

 

Chapter 2  History:A Tale of Two Cultures

 

Chapter  3 Contrasts:Compare the UNIX Philosophy with Others

P54

Multitasking Capability

1, Cooperative multitasking

2, Preemptive multitasking (UNIX)

 

Cooperating Process

Inexpensive process-spawning and easy inter-process communication(IPC) makes a whole ecology of small tools, pipes, and filters possible.

A subtle but important property of pipes and the other classic Unix IPC methods is that thay require communication between programs to be held down to a level of simplicity that encourages separationn of function. Conversely the result of having no equivalent of the pipe is that programs can only be designed to cooperate by build in full knowledge of each other's internals.

In the next piece of writing, the author figures the Microsoft programs do the converse way of UNIX.

 

P58

To design the perfect anti-Unix, make all file formats binary and opaque, and require heavyweight tools to read and edit them.

 

P61

Casual programming makes lower entry barrier to users/developers.

Operating system Comparisons

NT’s internal boundaries are extremely porous.

NT's CLI has become more and more neglected because the environment there is so sparse.

BeOS has astute design as UNIX but weak business strategy.

Linux does not include any code from the original Unix source tree, but it was designed from Unix standards to behave like a Unix.

The long-term goal of Linux is subsumption (emulating and absorbing)

 

Chapter 4 Modularity, Keep it Clean, Keep it Simple

P94

The Value of Detachment.

To design for compactness and orthogonality, start from zero.

It is well worth the mental effort to see how many preconceptions you can throw away, and whether the design becomes more compact and orthogonal as you do that. Possibilities for code reuse often result.

 

P99

Perfection is attained not when there is nothing more to add, but when there is nothing more to remove.

 

P103

Unix programmers know when not to use OO; and when they do use OO languages, they spend more effort on trying to keep their object designs uncluttered. As the author of The Elements of Networking Stype once observed in a slightly different context[Padlipsky]: “If you know what you're doing, three layers is enough; if you don't seventeen levels won't help".

 

Some questions to ask about any code you work on that might help you improve its modularity:

    How many global variables does it have? Global variables are modularity poison.......

    Is the size of your individual modules in Hatton's sweet spot? If no you may have a long-tern maintenance.

    Are the individual functions in your modules too large? If you can't describe a function's contract with its callers in one line, the function is probably too large.

   

P107

The Importance of Being Textual... there are good reasons the examples we'll see in Chapter7 are textual: reasons that hark back to Doug McIlroy's advice quoted in Chapter 1. Text streams are a valuable universal format because they're easy for human beings to read,write , and edit without specialized tools.

P109

Textual formats don't necessarily have much lower bit density than binary formats.

 

Chapter 5 Textuality

P120

Some rules about Unix textual file format conventions.

 

P131

Elegant code does much with little. Elegant code is not only correct but visibly, transparently correct.

Writing the code both transparency and discoverability will be hard to achieve.

 

Chapter 6 Transparency

P148

To design for transparency and discoverability, you need to apply every tactic for keeping your code simple, and also concentrate on the ways in which your code is a communication to other human beings.

......

These qualities in the human reaction to software are essential for reducing its bugginess and increasing its long-term maintainability.

 

Chapter 7 Multiprogramming

About IPC, IPC is attained through Pipeline, Wrappers, Slave Processes, Tempfiles, Signals, Sockets, Shared Memory

P180

Threads -- Thread or Menace ?

Why Threads Are a Bad Idea [Ousterhout96]

 

Chapter 8 Minilanguages

There are lots of bad reasons not to piggyback your imperative minilanguages on an existing scripting language. One of the few good ones is that you actually want to implement your own custom grammar for error checking...

These are reasons to use macro expansion with extreme caution. One of the long-term lessons of the Unix experience is that macros tend to create more problems than they solve. Modern languages and minilanguages designs have moved away from them.

 

Chapter 9 Generation

Data is more tractable than program logic.

It's good practice to move as much of the complexity in your design as possible away from procedural code and into data.

Data-Driven Programming...

 

Chapter 10 Configuration

.netrc, This kind of transprancy is important--much more important, actually, than the time economy of faster interpretion or the spce economy of a more compact and cryptic file format.

 

 

Chapter 11 Interface

The Rule of Least Surprise is a general principle in the design of all kinds of interfaces, not just software:"Do the least surprising thing". It's a consequence of the fact that human beings can only pay attention to one thing at one time(see The Humane Interface).)

P264

Unix programmers default toward making interfaces expressive and transparent, and are more willing to sacrifice ease to get these qualities.

P284

If your CLI program emits status messages to standard output, then programs that try to interpret that output will be put to the trouble of interpreting or discarding those messages. Better to send only real errors to standard error and not to emit unrequested data at all.

 

The user's vertical screen space is precious.

 

Junk messages are a careless waste of the human user's bandwidth.

 

In general, it's a bad style to tell the user things he already knows("Program is starting up...", or "Program is exiting" are two classic offenders).

 

If you want chatty progress messages for debugging purpose, disable them by default with a varbosity switch.


Chapter 12 Optimization

Premature optimization is the root of all evil.

Don't just do something, stand there!

But we always have to do optimization immidiately because of some pressure from picky customer.

 

When you have real-word evidence that your application is too slow, then (and only than) is the time to think about optimizing the code. Bet before you do more than think about optiomizing, measure.

Intuition is a poor guide to where the bottlenecks are.

 


Chapter 13 Languages

P323

C memory management is an enoumous source of complication and error. One study(cited in [Boehm]) estimates that 30% or 40% of development time is devoted to storage management for programs that manipulate complex data structure.  This did not even include the impact on debugging cost. While hard figures are lacking, many experienced programmers believe that memory-management bugs are the single largest source of persistent errors in real-world code.


Chapter 19 Open SOurce

P439

The rules of open-source development are simple.

1. Let the source be open.

2. Release early, release often.

3. Reward contribution with praise.


 

 


<think>我们被要求解释`fopen`函数中`"rb"`参数的含义,并说明其来源。 根据用户提供的文件打开模式说明,我们可以看到标准模式包括: r: 只读,文件开头 r+: 读写,文件开头 w: 只写,创建或截断文件 w+: 读写,创建或截断文件 a: 追加(写),文件末尾 a+: 读写,读从文件开头,写追加到文件末尾 注意:这些模式是针对文本文件的。而用户示例中使用的是`"rb"`,其中`b`代表二进制模式。 在标准C库中,`fopen`的模式字符串可以包含一个指定文本/二进制的字符: - 在模式字符串后添加`b`表示以二进制模式打开(例如`"rb"`,`"wb+"`等)。 - 如果不指定`b`,则默认以文本模式打开。 二进制模式与文本模式的主要区别: - 文本模式:在读取或写入时,可能会进行一些字符转换(例如,在Windows系统中,换行符`\n`会被转换成`\r\n`,而在读取时则反向转换)。 - 二进制模式:不对数据进行任何转换,直接按照文件中的原始字节进行读写。 因此,`"rb"`表示:以二进制模式打开文件进行读取。文件指针位于文件开头,且不会对文件内容进行任何转换。 关于`rb`参数的来源: - 它是C标准库的一部分,定义在`<stdio.h>`头文件中。 - 在POSIX系统(如Linux)中,二进制模式与文本模式没有区别(即`b`被忽略),但在Windows等系统中则有显著区别。 - 通常,在需要精确读取文件原始内容(如图片、视频、压缩文件等)时,应使用二进制模式;而处理文本文件时,可以使用文本模式(尤其在Windows下)以确保正确的换行符处理。 示例代码: ```c FILE *file = fopen(full_path, "rb"); // 以二进制读模式打开文件 if (file == NULL) { // 错误处理 } ``` 注意:如果文件不存在,`fopen`在`"r"`或`"rb"`模式下会返回NULL。 §§相关问题§§ 1. 在Windows系统中,文本模式和二进制模式在读写文件时具体有哪些区别? 2. 为什么在Linux系统下使用二进制模式与文本模式打开文件没有区别? 3. 当处理跨平台文件读写时,推荐使用文本模式还是二进制模式? 4. 使用`fopen`打开文件后,如何判断文件是否成功打开? 5. 除了`fopen`,还有哪些C标准库函数可以用于打开文件?</think>### `fopen` 函数中的 `"rb"` 模式详解 #### 模式参数解析 在 C 语言的 `fopen` 函数中: ```c FILE *fopen(const char *filename, const char *mode); ``` - **`"rb"` 的含义**: - `r`:只读模式 (read) - `b`:二进制模式 (binary) - 组合效果:以**二进制只读**方式打开文件 #### 关键特性 1. **二进制模式 vs 文本模式**: | 特性 | 二进制模式 (`b`) | 文本模式 (无 `b`) | |------|------------------|------------------| | 换行符转换 | 无转换 | `\n` ⇄ `\r\n` (Windows) | | 文件结束符 | 无特殊处理 | `Ctrl+Z` (0x1A) 可能被识别 | | 数据完整性 | 字节级精确 | 可能修改内容 | 2. **文件位置**: - 文件指针定位在**文件开头** - 允许使用 `fseek()` 随机访问 3. **错误处理**: - 文件不存在时返回 `NULL` - 需检查返回值:`if(file == NULL) { /* 错误处理 */ }` #### 参数来源标准 1. **C 语言标准库**: - 定义在 ISO C 标准 (C99/C11/C17) - 头文件:`<stdio.h>` - 参考文档:C 标准库手册 (如 POSIX.1, glibc 文档) 2. **跨平台行为**: ```mermaid graph LR A[Windows] --> B[二进制模式必需] C[Linux/macOS] --> D[b可省略] ``` - Windows:必须使用 `b` 避免换行符转换 - Unix-like 系统:`b` 可省略(无文本转换) #### 使用场景示例 ```c // 安全打开二进制文件(如图片/视频) FILE *file = fopen("image.jpg", "rb"); if (!file) { perror("文件打开失败"); exit(EXIT_FAILURE); } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值