]> git.tuebingen.mpg.de Git - aple.git/blob - Unix_Concepts.m4
Unix_Concepts: Only mark up I/O operations as code and not comma
[aple.git] / Unix_Concepts.m4
1 TITLE(«
2
3         Unix is user-friendly. It's just very selective about who
4         its friends are. -- Unknown
5
6 », __file__)
7
8 SECTION(«History and Philosophy»)
9
10 SUBSECTION(«Early Unix History»)
11
12 <p> Unix was created in 1969 as a successor of Multics, the
13 <em>MULTiplexed Information and Computing Service</em>, which had been
14 in use since the mid 1960s as the successor of CTSS, the <em>Compatible
15 Time-Sharing System</em> of the early 1960s. Multics aimed to get
16 CTSS right, but failed in this regard and was eventually discontinued
17 because of its complexity. The Unix approach was very different as it
18 was brainstormed by only three people and then implemented by Ken
19 Thompson at Bell Laboratories in two days. Unlike its predecessors it
20 focused on elegance and simplicity. The name was originally spelt
21 UNICS (<em>UNiplexed Information and Computing Service</em>) to
22 emphasize the contrast to Multics. </p>
23
24 <p> The original Unix implementation was written in assembly
25 language for the 18 bit processor of the PDP-7 "minicomputer", a
26 device of the size of a wardrobe which was considered small by the
27 standards of the day. Like all computers of this era, the PDP-7 was
28 not connected to a video screen. Instead, input had to be typed in on
29 the <em>console</em>, a device which looked much like an electric
30 typewriter. Output from the computer was printed on rolls of paper.
31 Since the assembly instructions could not easily be ported to different
32 hardware, Dennis Ritchie invented the C programming language in
33 1971. By 1973 the complete Unix implementation had been rewritten in C.
34 The C language was another corner stone in the history of Unix which
35 turned out to be very successful. While other programming languages
36 of that time have long been abandoned or play merely a niche role, C
37 is still one of the most widely used programming languages today. The
38 first Unix application was <code>roff</code>, a typesetting program
39 which is still ubiquitous as the manual pages which ship with every
40 Unix system are formatted with roff. </p>
41
42 <p> From the beginning, Thompson and his early collaborators encouraged
43 close communication between programmers, creating an early form of
44 community. Up to the present day, this "hacker culture" has been a
45 stimulus for countless improvements. Copies of Unix were distributed
46 on tapes, hand-signed with "Love, Ken". Over time many universities
47 contributed to Unix. By the end of the 1970s, Unix accumulated a
48 whole bunch of utilities that made it a fully flavored operating
49 system which was also free of any copyright claims. </p>
50
51 <p> Despite the primitive hardware of the time, the early Unix was
52 remarkably similar to modern Linux systems. For example, the task
53 scheduler, the hierarchical filesystem tree and the shell already
54 existed back then. </p>
55
56 SUBSECTION(«Networking»)
57
58 <p> The <em>Advanced Research Projects Agency</em> (ARPA) was a
59 military research unit that was part of the USA's department of
60 defence. It was established in the early 1960s with the mandate to
61 create systems that could survive a nuclear war. The agency created
62 the <em>arpanet</em>, the predecessor of today's internet, which was
63 designed to stay operational after subordinate network losses. By
64 the end of the 1960s and the early 1970s, the fundamental networking
65 protocols were established: telnet for remote login was standardized
66 in 1969, email (SMTP) in 1971, and the file transfer protocol (FTP)
67 in 1973. </p>
68
69 <p> By the end of the 1970s many Unix installations existed in
70 all parts of the world. However, the arpanet was mostly powered by
71 commercial Multics systems because Unix only had rudimentary network
72 support (UUCP, the <em>Unix to Unix copy</em>) which could copy files
73 over telephone lines via modems but not much more. This changed in
74 1983 when TCP/IP networking was developed by the ARPA to replace the
75 arpanet. Unix support for TCP/IP was developed at Berkeley University
76 which had become the "Mecca" for Unix development and started already
77 in 1977 to release their own Unix system named BSD, the <em>Berkeley
78 Software Distribution</em>. </p>
79
80 SUBSECTION(«Commercialization, POSIX and GNU»)
81
82 <p> With excellent networking support and no licensing issues, it
83 was only a matter of time until companies became interested in Unix
84 in order to make money. Several companies started to commercialize
85 Unix by adding features to the common code base but keeping their
86 improvements closed, effectively stopping the source code from being
87 freely distributable. At the same time Microsoft began to sell their
88 DOS operating system, targeting small businesses and the home market.
89 DOS lacked many features that Unix already had for a decade, like
90 multi-tasking and multi-user support, but it did run on the cheap
91 Intel 286 processors that were too weak for Unix. </p>
92
93 <p> By 1985 the commercialization of Unix and the success of Microsoft
94 had damaged the Unix community badly. But also the various companies
95 that sold their particular proprietary Unix brand realized that
96 too many incompatible Unix implementations would only hurt their
97 business. That's where the Computer Society of the <em>Institute of
98 Electrical and Electronics Engineers</em> (IEEE) became involved
99 in Unix. The IEEE is an organization which was already founded in
100 1946 to advance the theory, practice, and application of computer
101 technology. This organization created POSIX, the <em>Portable Operating
102 System Interface for Unix</em>, which is a family of specifications
103 for maintaining compatibility between operating systems. The first
104 version of POSIX was published in 1988. It covered several command
105 line utilities including <code>vi(1)</code> and <code>awk(1)</code>,
106 the shell scripting language, application programmer interfaces (APIs)
107 for I/O (input/output) and networking, and more. Up to the present
108 day POSIX is maintained by the IEEE and new revisions of the POSIX
109 standard are published regularly. </p>
110
111 <p> In 1983 Richard Stallman launched the GNU project and the Free
112 Software Foundation as a reaction to the ongoing commercialization
113 of Unix. GNU, which is is a recursive acronym for "GNU's not Unix",
114 aimed to keep the Unix source code free, or to replace non-free parts
115 by open source equivalents. To this aim the GNU project created
116 the <em>GNU General Public License</em> (GPL), which requires not
117 only the source code to stay free, but also that all subsequent
118 modifications to the code base remain free. By the end of the 80s,
119 the GNU toolset had become a full developer software stack licensed
120 under the GPL. This set of software packages was complemented by
121 the <em>X window system</em>, which was also released under a free
122 license and enabled programmers to build graphical applications for
123 desktop systems.  Moreover, the first open source scripting language,
124 <em>perl</em>, was released in 1987. </p>
125
126 SUBSECTION(«Linux»)
127
128 <p> In 1985 Intel announced the 386 processor which, unlike its 286
129 predecessor, was powerful enough to run Unix. There were efforts to
130 port the Unix operating system kernel to this hardware, but these
131 efforts were impaired by pending lawsuits about who owns the copyright
132 on the BSD source code. Due to the unclear legal situation of the BSD
133 code, the major missing piece in the GNU toolset was a free operating
134 system kernel. This hole was filled in 1991 when Linus Torvalds,
135 a student from Helsinki in Finland, announced the first version of
136 his <em>Linux</em> kernel. </p>
137
138 <p> Linux did not repeat the licensing problems of the original Unix
139 because the Linux source code was written from scratch and licensed
140 under the GPL. Due to this difference many developers moved from
141 Unix to Linux, so Linux grew quickly and started soon to outperform
142 the commercial Unix kernels in almost every benchmark. The cheap 386
143 hardware, the Linux kernel, the GNU toolset and the graphical user
144 interface based on the X window system facilitated cheap workstations
145 which ran a complete open source software stack. </p>
146
147 <p> The success of Linux, or <em>GNU/Linux</em> as some prefer to
148 call it for reasons that should now be clear, steadily increased over
149 time. In 2003 the SCO group, a company which sold a proprietary Unix
150 system, was unhappy about this progress and sued IBM, which offered
151 various Linux products. SCO claimed to be the owner of Unix, and that
152 Linux contained "millions of lines" of code copied from Unix. SCO's
153 lawyers argued that the success of Linux originated from this theft
154 of intellectual property and asked for $5 billion as compensation
155 for the resulting losses. The company also tried to collect taxes
156 from other Linux users. Microsoft funded SCO in these efforts. </p>
157
158 <p> In the end SCO lost the lawsuit since it was evident that all that
159 copied code never existed. In fact, the court ruled that SCO did not
160 even own the Unix copyrights to begin with. Another fun fact is that
161 the large number of bugs in the early Linux code actually helped to
162 prove that Linux was original work. The long term effects of this
163 lawsuit, an improved position of Linux and its ecosystem, last until
164 the presence. Commercial Unix systems have become irrelevant as Linux
165 runs on a wide variety of machines ranging from supercomputers to
166 workstations, smart phones and IOT (internet of things) devices with
167 very limited resources. </p>
168
169 <p> While SCO went bankrupt eventually, some of the companies which
170 almost killed Unix by maximizing their own profit still exist, and
171 make money with Linux today. However, they had to adjust their
172 business model in order to comply with the GPL. Rather than selling
173 proprietary software, they bundle open source software and sell
174 support to paying customers. Some companies also sell hardware with
175 Linux pre-installed. </p>
176
177 SUBSECTION(«Linux Distributions»)
178
179 <p> A <em>Linux Distribution</em> is a conglomeration of free software,
180 including the Linux kernel, the GNU toolset and the X window system,
181 plus possibly other, proprietary software on top of that. Usually a
182 distribution also includes an installer and a package manager to
183 make it easy to install and update packages according to the users'
184 needs. </p>
185
186 <p> There are hundreds of Linux distributions, and new distributions
187 are created all the time while others are discontinued. Many
188 distributions are backed by companies which target specific
189 classes of users or hardware, but there are also non-commercial
190 Linux distributions which are solely driven by a community of
191 volunteers. </p>
192
193 <p> One of the most popular company-backed Linux distributions is
194 <em>Ubuntu</em>, which is led since 2004 by the UK-based Canonical Ltd.
195 It targets unskilled desktop users which would like to switch away
196 from Microsoft Windows. One reason for the popularity of Ubuntu
197 is that it is very easy to install on standard desktop and laptop
198 hardware. A distinguishing feature of Ubuntu is its strict release
199 cycles: New versions are released in April and October of each year,
200 and every fourth release is a <em>long-term support</em> (LTS) release
201 which will be supported for at least five years. Ubuntu also features
202 a variant for server hardware which contains a different Linux kernel
203 and ships with most desktop packages excluded. </p>
204
205 <p> The main community-driven Linux distribution is
206 <em>Debian</em>. The Debian project was founded in 1993 and the first
207 stable version was released in 1996. Debian is used as the basis for
208 many other distributions. In fact, Ubuntu is based on Debian. The
209 development of Debian closely follows the Unix culture in that it
210 is developed openly and distributed freely. A team of about 1000
211 core developers work together with countless package maintainers
212 according to the Debian Social Contract, the Debian Constitution,
213 and the Debian Free Software Guidelines. </p>
214
215 EXERCISES()
216
217 <ul>
218         <li> Run <code>uname -a</code> on various Unix machines to see the
219         OS type and the kernel version. </li>
220
221         <li> Explore the <a
222         href="https://upload.wikimedia.org/wikipedia/commons/7/77/Unix_history-simple.svg">Unix
223         time line</a>. </li>
224
225         <li> Try out the <a
226         href="http://www.gnu.org/cgi-bin/license-quiz.cgi">Free Software
227         licensing quiz</a>. </li>
228
229         <li> On a Debian or Ubuntu system, run <code>aptitude search
230         python</code> to list all python-related Ubuntu packages. Run
231         <code>aptitude show python-biopython</code> to see the description
232         of the biopython package. Repeat with different search patterns and
233         packages. </li>
234
235         <li> The Debian Social Contract (DSC) describes the agenda of Debian.
236         Find the DSC online, read it and form your own opinion about the key
237         points stated in this document. </li>
238 </ul>
239
240 SECTION(«Characteristics of a Unix system»)
241
242 <p> After having briefly reviewed the history of Unix, we now look
243 closer at the various components which comprise a Unix system and
244 which distinguish Unix from other operating systems. We focus on
245 general design patterns that have existed since the early Unix days
246 and are still present on recent Linux systems. </p>
247
248 SUBSECTION(«Single Hierarchy of Files»)
249
250 <p> The most striking difference between Unix and Windows is perhaps
251 that on Unix the files of all devices are combined to form a single
252 hierarchy with no concept of drive letters. When the system boots,
253 there is only one device, the <em>root device</em>, which contains the
254 <em>root directory</em>. To make the files of other devices visible,
255 the <em>mount</em> operation must be employed. This operation attaches
256 the file hierarchy of the given device to the existing hierarchy
257 at a given location which is then called the <em>mountpoint</em>
258 of the device. Mountpoints are thus the locations in the hierarchy
259 where the underlying storage device changes. </p>
260
261 <p> The root directory contains a couple of well-known subdirectories,
262 each of which is supposed to contain files of a certain type or for
263 a certain purpose. The following table lists a subset:
264
265 <ul>
266         <li> <code>/bin</code>: Essential commands for all users </li>
267         <li> <code>/sbin</code>: Essential system binaries </li>
268         <li> <code>/lib</code>: Essential libraries </li>
269         <li> <code>/usr</code>: Non-essential read-only user data </li>
270         <li> <code>/etc</code>: Static configuration files </li>
271         <li> <code>/home</code>: Home directories </li>
272         <li> <code>/tmp</code>: Temporary files </li>
273         <li> <code>/run</code>: Files which describe the state of running programs </li>
274         <li> <code>/var</code>: Log and spool files </li>
275 </ul>
276
277 <p> The <em>Filesystem Hierarchy Standard</em> describes the various
278 subdirectories in more detail. The exercises ask the reader to become
279 acquainted with this directory structure. </p>
280
281 SUBSECTION(«POSIX Commands and Shell»)
282
283 <p> The Filesystem Hierarchy Standard lists <code>/bin</code>
284 and <code>/sbin</code> and several other directories for executable
285 files. The POSIX standard defines which executables must exist in one
286 of these directories for the system to be POSIX-compliant.  Well over
287 100 <em>POSIX commands</em> are listed in the XCU volume of this
288 standard. Besides the names of the commands, the general behaviour
289 of each and the set of command line options and their semantics are
290 described.  POSIX versions are designed with backwards compatibility
291 in mind. For example, a new POSIX version might require a command
292 to support additional command line options, but existing options are
293 never dropped and never change semantics in incompatible ways. The
294 target audience of the POSIX document are programmers who implement
295 and maintain the POSIX commands and users which want to keep their
296 software portable across different Unix flavors. </p>
297
298 <p> One of the POSIX commands is the <em>shell</em>,
299 <code>/bin/sh</code>, an interpreter that reads input expressed in
300 the <em>shell command language</em>, which is also part of POSIX.
301 The shell transforms the input in various ways to produce commands
302 and then executes these commands. The user may enter shell code
303 (i.e., code written in the shell command language) interactively at
304 the <em>command prompt</em>, or supply the input for the shell as a
305 <em>shell script</em>, a text file which contains shell code. Shell
306 scripts which only contain POSIX commands and use only POSIX options
307 are portable between different shell implementations and between
308 different Unix flavors. They should therefore never cease to work after
309 an upgrade. Among the many available POSIX shell implementations,
310 <em>GNU bash</em> is one of the more popular choices. Bash is fully
311 POSIX compatible and offers many more features on top of what is
312 required by POSIX. </p>
313
314 <p> Several implementations of the POSIX commands exist. On Linux
315 the GNU implementation is typically installed while FreeBSD, NetBSD
316 and MacOS contain the BSD versions. Although all implementations
317 are POSIX-compliant, they differ considerably because different
318 implementations support different sets of additional features and
319 options which are not required by POSIX. These extensions are not
320 portable, and should thus be avoided in shell scripts that must work
321 on different Unix flavors. </p>
322
323 <p> In addition to the POSIX commands, a typical Unix system might well
324 contain thousands of other commands. This illustrates another aspect
325 that is characteristic for Unix: Tools should do only one specific
326 task, and do it well. The operating system provides mechanisms
327 to combine the simple commands in order to form more powerful
328 programs. For example, commands can be <em>chained</em> together so
329 that the output of one command becomes the input for the next command
330 in the chain. This is the idea behind <em>pipes</em>, a Unix concept
331 which dates back to 1973 and which is also covered by POSIX. We shall
332 come back to pipes and related concepts in a later section. </p>
333
334 SUBSECTION(«Multi-User, Multi-Tasking, Isolation»)
335
336 <p> From the very beginning Unix was designed to be a multi-user
337 and a multi-tasking operating system. That is, it could run multiple
338 programs on behalf of different users independently of each other and
339 isolated from each other. This design was chosen to improve hardware
340 utilization and robustness. In contrast, DOS and early versions
341 of Windows were designed for <em>personal computing</em> (PC) and
342 had no notion of user accounts, access permissions or isolation.
343 This resulted in an unstable system because a single misbehaving
344 program was enough to take down the whole system. Therefore these
345 features had to be retrofitted later.  </p>
346
347 <p> While multi-tasking makes all tasks appear to run simultaneously
348 even if there are more tasks than CPUs, isolation refers to
349 <em>memory protection</em>, a mechanism which prevents applications
350 from interfering with each other and with the internals of the
351 operating system. A running Unix system maintains two sets of
352 running tasks: besides the <em>application tasks</em> there is
353 also a set of <em>kernel tasks</em>. Unlike the application tasks,
354 the kernel tasks are privileged in that they can access the memory
355 of the application tasks while applications tasks can only access
356 their own memory. Isolation is achieved by a hardware concept called
357 <em>protection domains</em>, which existed already in Multics and thus
358 predates Unix. In the simplest case, there are only two protection
359 domains: a privileged domain called <em>ring 0</em> for the kernel
360 tasks, and an unprivileged domain for application tasks, also called
361 <em>user processes</em> in this context. The CPU is always aware
362 of the current protection domain as this information is stored in a
363 special CPU register.
364
365 SUBSECTION(«System Calls and the C POSIX Library»)
366
367 <p> Only when the CPU is running in the privileged ring 0 domain
368 (also known as <em>kernel mode</em>, as opposed to <em>user mode</em>
369 for application tasks), it can interact directly with hardware and
370 memory. If an application wants to access hardware, for example read a
371 data block from a storage device, it can not do so by itself. Instead,
372 it has to ask the operating system to perform the read operation
373 on behalf of the application. This is done by issuing a <em>system
374 call</em>. Like function calls, system calls interrupt the current
375 program, continue execution at a different address and eventually
376 return to the instruction right after the call. However, in addition
377 to this, they also cause the CPU to enter kernel mode so that it can
378 perform the privileged operation. When the system call has done its
379 work and is about to return to the application, the protection domain
380 is changed again to let the CPU re-enter user mode. </p>
381
382 <p> The system calls thus define the interface between applications
383 and the operating system. For backwards compatibility it is of utmost
384 importance that system calls never change semantics in an incompatible
385 way. Moreover, system calls must never be removed because this would
386 again break existing applications. The syntax and the semantics
387 of many system calls are specified in POSIX, although POSIX does
388 not distinguish between functions and system calls and refers to
389 both as <em>system functions</em>. This is because system calls are
390 typically not performed by the application directly. Instead, if an
391 application calls, for example, <code>read()</code>, it actually calls
392 the compatibility wrapper for the <code>read</code> system call which
393 is implemented as a function in the <em>C POSIX Library</em> (libc),
394 which ships with every Unix system. It is this library which does the
395 hard work, like figuring out which system calls are supported on the
396 currently running kernel, and how kernel mode must be entered on this
397 CPU type. Like the POSIX commands, the system functions described in
398 POSIX never change in incompatible ways, so programs which exclusively
399 use POSIX system functions are portable between different Unix flavors
400 and stay operational after an upgrade. </p>
401
402 SUBSECTION(«Multi-Layer Configuration Through Text Files»)
403
404 <p> On a multi-user system it becomes necessary to configure programs
405 according to each user's personal preferences. The Unix way to
406 achieve this is to provide four levels of configuration options
407 for each program. First, there are the built-in defaults which are
408 provided by the author of the program. Next, there is the system-wide
409 configuration that is controlled by the administrator. Third,
410 there is the user-defined configuration, and finally there are the
411 command line options. Each time the program is executed, the four
412 sets of configuration options are applied one after another so
413 that the later sets of options override the earlier settings. The
414 system-wide configuration is stored in <code>/etc</code> while the
415 user-defined configuration is stored in that user's home directory.
416 Both are are simple text files that can be examined and modified with
417 any text editor. This makes it easy to compare two configurations
418 and to transfer the configuration across different machines or user
419 accounts. </p>
420
421 SUBSECTION(«Everything is a File»)
422
423 <p> Another mantra which is often heard in connection with Unix is
424 <em>everything is a file</em>. This phrase, while certainly catchy,
425 is slightly incorrect. A more precise version would be <em>everything
426 is controlled by a file descriptor</em>, or, as Ritchie and Thompson
427 stated it, Unix has <em>compatible file, device, and inter-process
428 I/O</em>. Modern Unix systems have pushed this idea further and employ
429 file descriptors also for networking, process management, system
430 configuration, and for certain types of events. The file descriptor
431 concept is thus an abstraction which hides the differences between the
432 objects the file descriptors refer to. It provides a uniform interface
433 for the application programmer who does not need to care about whether
434 a file descriptor refers to a file, a network connection, a peripheral
435 device or something else because the basic I/O operations like open,
436 read, write are the same. </p>
437
438 <p> File descriptors are ubiquitous since every Unix program uses
439 them, albeit perhaps implicitly via higher-level interfaces provided
440 by a scripting language. We shall return to this topic when we discuss
441 processes. </p>
442
443 SUBSECTION(«Manual Pages»)
444
445 <p> All POSIX commands and most other programs are installed along
446 with one or more <em>man pages</em> (short for <em>manual pages</em>),
447 which are plain text files that can be formatted and displayed in
448 various ways. This concept was introduced in 1971 as part of the
449 <em>Unix Programmer's Manual</em>.  The characteristic page layout
450 and the typical sections (NAME, SYNOPSIS, DESCRIPTION, EXAMPLES,
451 SEE ALSO) of a man page have not changed since then. The POSIX
452 <code>man</code> command is used to view man pages in a terminal. For
453 example, the command <code>man ls</code> opens the man page of the
454 <code>ls</code> command, and <code>man man</code> shows the man page
455 of the <code>man</code> command itself. Most implementations also
456 maintain a database of the existing man pages and provide additional
457 commands to query this database. For example, the <code>whatis</code>
458 command prints the one-line description of all man pages which match
459 a pattern while the <code>apropos</code> command searches the manual
460 page names and descriptions. </p>
461
462 <p> In addition to the man pages for commands, there are man pages for
463 system calls, library functions, configuration files and more. Each
464 man page belongs to one of several <em>man sections</em>. For example,
465 the aforementioned man pages for <code>ls</code> and <code>man</code>
466 are part of section 1 (user commands) while section 2 is reserved for
467 system calls and section 8 for administration commands that can only be
468 executed by privileged users. By convention, to indicate which section
469 a command or a function belongs to, the man section is appended in
470 parenthesis as in <code>mount(8)</code>. Most Unix systems also offer
471 translated man pages for many languages as an optional package. Note
472 that the same name may refer to more than one man page. For example
473 there is <code>kill(1)</code> for the user command that kills processes
474 and also <code>kill(2)</code> which describes the corresponding system
475 call. To open the man page of a specific section, one may use a command
476 like <code>man 2 kill</code>.  The <code>MANSECT</code> environment
477 variable can be set to a colon-delimited list of man sections to
478 change the order in which the man sections are searched. </p>
479
480 <p> Consulting the local man pages rather than searching the web has
481 some advantages. Most importantly, the local pages will always give
482 correct answers since they always match the installed software while
483 there is no such relationship between a particular web documentation
484 page and the version of the software package that is installed on the
485 local computer. Working with man pages is also faster, works offline
486 and helps the user to stay focused on the topic at hand. </p>
487
488 EXERCISES()
489
490 <ul>
491         <li> Run <code>df</code> on as many systems as possible to see the
492         mount points of each filesystem. Then discuss the pros and cons of
493         a single file hierarchy as opposed to one hierarchy per device. </li>
494
495         <li> Run <code>ls /</code> to list all top-level subdirectories of
496         the root file system and discuss the purpose of each. Consult the
497         Filesystem Hierarchy Standard if in doubt. </li>
498
499         <li> Execute <code>cd / && mc</code> and start surfing at the root
500          directory.  </li>
501
502         <li> Compare the list of top-level directories that exist on different
503         Unix systems, for example Linux and MacOS. </li>
504
505         <li> Find out which type of files are supposed to be stored in
506         <code>/usr/local/bin</code>. Run <code>ls /usr/local/bin</code>
507         to list this directory.  </li>
508
509         <li> Find out what the term <em>bashism</em> means and learn how to
510         avoid bashishms. </li>
511
512         <li> Find the POSIX specification of the <code>cp(1)</code> command
513         online and compare the set of options with the options supported by
514         the GNU version of that command, as obtained with <code>man cp</code>
515         on a Linux system. </li>
516
517         <li>&nbsp;
518                 <ul>
519                         <li> Run <code>time ls /</code> and discuss the meaning of
520                         the three time values shown at the end of the output (see
521                         <code>bash(1)</code>). </li>
522
523                         <li> Guess the user/real and the sys/real ratios for the following
524                         commands. Answer, before you run the commands.
525
526                                 <ul>
527                                         <li> <code>time head -c 100000000 /dev/urandom > /dev/null</code> </li>
528
529                                         <li> <code>i=0; time while ((i++ &lt; 1000000)); do :; done</code>
530                                         </li>
531                                 </ul>
532                         </li>
533
534                         <li> Run the above two commands again, this time run
535                         <code>htop(1)</code> in parallel on another terminal and observe the
536                         difference. </li>
537                 </ul>
538         </li>
539
540         <li> On a Linux system, check the list of all system calls in
541         <code>syscalls(8)</code>. </li>
542
543         <li> The <code>strace(1)</code> command prints the system calls that
544         the given command performs. Guess how many system calls the command
545         <code>ls -l</code> will make.  Run <code>strace -c ls -l</code> for
546         the answer. Read the <code>strace(1)</code> man page to find suitable
547         command line options to only see the system calls which try to open
548         a file. </li>
549
550         <li> Guess how many man pages a given system has. Run <code>whatis -w
551         '*' | wc -l</code> to see how close your guess was. </li>
552
553         <li> Search the web for "cp(1) manual page" and count how many
554         <em>different</em> manual pages are shown in the first 20 hits. </li>
555 </ul>
556
557 HOMEWORK(«
558
559 Think about printers, sound cards, or displays as a file. Specifically,
560 describe what <code>open, read</code>, and <code>write</code> should
561 mean for these devices.
562
563 », «
564
565 Opening would establish a (probably exclusive) connection
566 to the device.  Reading from the file descriptor returned by
567 <code>open(2)</code> could return all kinds of status information,
568 like the type, model and capabilities of the device. For example,
569 printers could return the number of paper trays, the amount of toner
570 left etc. Writing to the file descriptor would cause output on the
571 device. This would mean to print the text that is written, play the
572 audio samples, or show the given text on the display. The point to
573 take away is that the <code>open, read, write</code> interface is a
574 generic concept that works for different kinds of devices, not only
575 for storing data in a file on a hard disk.
576
577 »)
578
579 SECTION(«Paths, Files and Directories»)
580
581 In this section we look in some detail at paths, at a matching
582 language for paths, and at the connection between paths and files. We
583 then describe the seven Unix file types and how file metadata are
584 stored. We conclude with the characteristics of soft and hard links.
585
586 SUBSECTION(«Paths»)
587
588 <p> The path concept was introduced in the 1960s with the Multics
589 operating system. Paths will be familiar to the reader because
590 they are often specified as arguments to commands. Also many
591 system calls receive a path argument. A path is a non-empty
592 string of <em>path components</em> which are separated by slash
593 characters. An <em>absolute path</em> is a path that starts with a
594 slash, all other paths are called <em>relative</em>. A relative path
595 has to be interpreted within a context that implies the leading
596 part of the path. For example, if the implied leading part is
597 <code>/foo/bar</code>, the relative path <code>baz/qux</code> is
598 equivalent to the absolute path <code>/foo/bar/baz/qux</code>. </p>
599
600 <p> Given a path, there may or may not exist a file or a
601 directory that corresponds to the path. <em>Path lookup</em> is the
602 operation which determines the answer to this question, taking the
603 implied leading part into account in case of relative paths. This
604 operation is always performed within the kernel and turns out to
605 be surprisingly complex due to concurrency and performance issues.
606 Consult <code>path_resolution(7)</code> on a Linux system to learn
607 more about how pathnames are resolved to files. </p>
608
609 <p> If a path was successfully looked up, each path component up to the
610 second-last refers to an existing directory while the last component
611 refers to either a file or a directory. In both cases the directory
612 identified by the second-last component contains an entry named by the
613 last component. We call those paths <em>valid</em>. The valid paths
614 give rise to a rooted tree whose interior nodes are directories and
615 whose leaf nodes are files or directories. Note that the validity of a
616 path depends on the set of existing files, not just on the path itself,
617 and that a valid path may become invalid at any time, for example if
618 a file is deleted or renamed. Many system calls which receive a path
619 argument perform path lookup and fail with the <code>No such file or
620 directory</code> error if the lookup operation fails. </p>
621
622 <p> It depends on the underlying filesystem whether the path components
623 are <em>case-sensitive</em> or <em>case-insensitive</em>. That is,
624 whether paths which differ only in capitalization (for example
625 <code>foo</code> and <code>Foo</code>) refer to the same file.
626 Since the hierarchy of files may be comprised of several filesystems,
627 some components of the path may be case-sensitive while others are
628 case-insensitive. As a rule of thumb, Unix filesystems are case
629 sensitive while Microsoft filesystems are case-insensitive even when
630 mounted on a Unix system. </p>
631
632 <p> Path components may contain every character except the Null
633 character and the slash. In particular, space and newline characters
634 are allowed. However, while dots are allowed in path components if
635 they are used together with other characters, the path components
636 <code>.</code> and <code>..</code> have a special meaning: every
637 directory contains two subdirectories named <code>.</code> and
638 <code>..</code> which refer to the directory itself and its parent
639 directory, respectively. </p>
640
641 SUBSECTION(«Globbing»)
642
643 <p> Globbing, also known as <em>pathname expansion</em>, is a pattern
644 matching language for paths which was already present in the earliest
645 Unix versions. The glob operation generates a set of valid paths from
646 a <em>glob pattern</em> by replacing the pattern by all <em>matching
647 paths</em>. </p>
648
649 <p> Glob patterns may contain special characters called
650 <em>wildcards</em>. The wildcard characters are: </p>
651
652         <ul>
653                 <li> <code>*</code>: match any string, </li>
654                 <li> <code>?</code>: match any simple character, </li>
655                 <li> <code>[...]</code>: match any of the enclosed characters. </li>
656         </ul>
657
658 <p> The complete syntax rules for glob patterns and the exact
659 semantics for pattern matching are described in POSIX and in
660 <code>glob(7)</code>. Any POSIX-compliant shell performs globbing
661 to construct the command to be executed from the line entered at
662 the prompt. However, POSIX also demands system functions which make
663 globbing available to other applications. These are implemented as
664 part of libc. </p>
665
666
667 <p> There are a few quirks related to globbing which are worth to
668 point out. First, if no valid path matches the given pattern, the
669 expansion of the pattern is, by definition according to POSIX, the
670 pattern itself. This can lead to unexpected results. Second, files
671 which start with a dot (so-called <em>hidden</em> files) must be
672 matched explicitly. For example, <code>rm *</code> does <em>not</em>
673 remove these files. Third, the tilde character is <em>no</em> wildcard,
674 although it is also expanded by the shell. See the exercises for more
675 examples. </p>
676
677 <p> POSIX globbing has some limitations. For example, there is no
678 glob pattern which matches exactly those files that start with an
679 arbitrary number of <code>a</code> characters. To overcome these
680 limitations, some shells extend the matching language by implementing
681 <em>extended glob patterns</em> which are not covered by POSIX. For
682 example, if extended globbing feature of <code>bash(1)</code> is
683 activated via the <code>extglob</code> option, the extended glob
684 pattern <code>+(a)</code> matches the above set of files. </p>
685
686 SUBSECTION(«File Types»)
687
688 We have seen that all but the last component of a valid path refer
689 to directories while the last component may refer to either a file
690 or a directory. The first character in the output of <code>ls
691 -l</code> indicates the type of the last path component: for
692 directories a <code>d</code> character is shown while files (also
693 called <em>regular</em> files in this context) get a hyphen character
694 (<code>-</code>). Besides directories and regular files, the following
695 special file types exist:
696
697 <dl>
698         <dt> Soft link (<code>l</code>) </dt>
699
700         <dd> A file which acts as a pointer to another file. We shall cover
701         links in a dedicated subsection below. </dd>
702
703         <dt> Device node (<code>c</code> and <code>b</code>) </dt>
704
705         <dd> Also called <em>device special</em>. These files refer to devices
706         on the local system. Device nodes come in two flavors: character
707         devices (<code>c</code>) and block devices (<code>b</code>). Regardless
708         of the flavor, each device node has a major and a minor number
709         associated with it. The major number indicates the type of the
710         device (e.g. a hard drive, a serial connector, etc.) while the
711         minor number enumerates devices of the same type. On most systems
712         the device nodes are created and deleted on the fly as the set of
713         connected devices changes, for example due to a USB device being
714         added or removed. However, device nodes can also be created manually
715         with the <code>mknod(1)</code> command or the <code>mknod(2)</code>
716         system call. Device nodes do not necessarily correspond to physical
717         devices. In fact, POSIX demands the existence of a couple of
718         <em>virtual devices</em> with certain properties. We look at some of
719         these in the exercises. The access to device nodes which do correspond
720         to physical devices is usually restricted to privileged users. </dd>
721
722         <dt> Socket (<code>s</code>) </dt>
723
724         <dd> Sockets provide an interface between a running program and the
725         network stack of the kernel. They are subdivided into <em>address
726         families</em> which correspond to the various network protocols. For
727         example, the <code>AF_INET</code> and <code>AF_INET6</code> address
728         families are for internet protocols (IP) while <code>AF_LOCAL</code>
729         (also known as <code>AF_UNIX</code>) is used for communication between
730         processes on the same machine. These local sockets are also called
731         <em>Unix domain sockets</em>. They can be bound to a path which
732         refers to a file of type socket. Regardless of the address family,
733         processes can exchange data via sockets in both directions, but
734         the local sockets support additional features, like passing process
735         credentials to other processes. </dd>
736
737         <dt> Fifo (<code>p</code>) </dt>
738
739         <dd> Files of type <em>fifo</em> are also known as <em>named
740         pipes</em>. They associate a path with a kernel object that provides a
741         <em>First In, First Out</em> data channel for user space programs. Data
742         written to the fifo by one program can be read back by another program
743         in the same order. Fifos are created with the <code>mkfifo(1)</code>
744         command or the <code>mkfifo(3)</code> library function. </dd>
745 </dl>
746
747 <p> Note that the type of a file is never inferred from the path.
748 In particular the suffix of the path (everything after the last
749 dot) is just a convention and has no strict connection to the file
750 type. Also there is no difference between text and binary files. </p>
751
752 SUBSECTION(«Metadata and Inodes»)
753
754 <p> The <code>stat(2)</code> system call returns the metadata
755 of the file or directory that corresponds to the given path. The
756 <code>stat(1)</code> command is a simple program which executes this
757 system call and prints the thusly obtained metadata in human-readable
758 form, including the file type. This is done without looking at the
759 contents of the file because metadata are stored in a special area
760 called the <em>inode</em>. All types of files (including directories)
761 have an associated inode. Besides the file type, the inode stores
762 several other properties prescribed by POSIX. For example the file
763 size, the owner and group IDs, and the access permissions are all
764 stored in the inode. Moreover, POSIX requires to maintain three
765 timestamps in each inode: </p>
766
767 <ul>
768         <li> modification time (mtime): time of last content change. </li>
769
770         <li> access time (atime): time of last access. </li>
771
772         <li> status change time (ctime): time of last modification to the
773         inode. </li>
774 </ul>
775
776 <p> To illustrate the difference between the mtime and the ctime,
777 consider the <code>chgrp(1)</code> command which changes the group
778 ID of the file or directory identified by its path argument. This
779 command sets the ctime to the current time while the mtime is left
780 unmodified. On the other hand, commands which modify the contents of
781 a file, such as <code>echo foo >> bar</code>, change both the mtime
782 and the ctime. </p>
783
784 <p> The inode of each file or directory contains twelve <em>mode
785 bits</em>, nine of which are the <em>permission bits</em> which
786 control who is allowed to access the file or directory, and how. The
787 permission bits are broken up into three classes called <em>user</em>
788 (<code>u</code>), <em>group</em> (<code>g</code>) and <em>others</em>
789 (<code>o</code>). Some texts refer to the first and last class as
790 "owner" and "world" instead, but we won't use this naming to avoid
791 confusion. Each class contains three bits. The bits of the "user"
792 class apply to the file owner, that is, the user whose ID is stored in
793 the inode. The "group" category applies to all non-owners who belong
794 to the group whose ID is stored in the inode. The third category
795 applies to all remaining users. The three bits of each class refer to
796 read/write/execute permission. They are therefore named <code>r</code>,
797 <code>w</code> and <code>x</code>, respectively. The permission
798 bits mean different things for directories and non-directories,
799 as described below. </p>
800
801 <table>
802         <tr>
803                 <th> &nbsp;&nbsp; </th>
804                 <th> Directories </th>
805                 <th> Non-directories </th>
806         </tr> <tr>
807                 <th> <code>r</code> </th>
808
809                 <td> The permission to list the directory contents. More precisely,
810                 this bit grants the permission to call <code>opendir(3)</code>
811                 to obtain a handle to the directory which can then be passed to
812                 <code>readdir(3)</code> to obtain the directory contents. </td>
813
814                 <td> If read permission is granted, the <code>open(2)</code> system
815                 call does not fail with the <code>permission denied</code> error,
816                 provided the file is opened in read-only mode. The system call may
817                 fail for other reasons, though.
818
819         </tr> <tr>
820                 <th> <code>w</code> </th>
821
822                 <td> The permission to add or remove directory entries. That is,
823                 to create new files or to remove existing files. Note that write
824                 permission is not required for the file that is being removed. </td>
825
826                 <td> Permission to open the file in write-only mode in order
827                 to perform subsequent operations like <code>write(2)</code>
828                 and <code>truncate(2)</code> which change the contents of the
829                 file. Non-directories are often opened with the intention to both
830                 read and write. Naturally, such opens require both read and write
831                 permissions. </td>
832
833         </tr> <tr>
834                 <th> <code>x</code> </th>
835
836                 <td> The permission to <em>search</em> the directory. Searching
837                 a directory means to access its entries, either by retrieving
838                 inode information with <code>stat(2)</code> or by calling
839                 <code>open(2)</code> on a directory entry. </td>
840
841                 <td> Run the file. This applies to <em>binary executables</em> as well
842                 as to text files which start with a <em>shebang</em>, <code>#!</code>,
843                 followed by the path to an interpreter. We shall cover file execution
844                 in more detail below. </td>
845
846         </tr>
847 </table>
848
849 <p> To run the regular file <code>/foo/bar/baz</code>, search
850 permission is needed for both <code>foo</code> and <code>bar</code>,
851 and execute permission is needed for <code>baz</code>. Similarly, to
852 open the regular file <code>foo/bar</code> for reading, we need execute
853 permissions on the current working directory and on <code>foo</code>,
854 and read permissions on <code>bar</code>. </p>
855
856 <p> A <em>numeric permission mode</em> is a three octal digit (0-7)
857 number, where the digits correspond to the user, group, other classes
858 described above, in that order. The value of each digit is derived by
859 adding up the bits with values 4 (read), 2 (write), and 1 (execute).
860 The following table lists all eight possibilities for each of the
861 three digits. </p>
862
863 <table>
864         <tr>
865                 <th> Octal Value </th>
866                 <th> Symbolic Representation </th>
867                 <th> Meaning </th>
868         </tr> <tr>
869                 <td> 0 </td>
870                 <td> <code>---</code> </td>
871                 <td> no permissions at all </td>
872         </tr> <tr>
873                 <td> 1 </td>
874                 <td> <code>--x</code> </td>
875                 <td> only execute permission </td>
876         </tr> <tr>
877                 <td> 2 </td>
878                 <td> <code>-w-</code> </td>
879                 <td> only write permission </td>
880         </tr> <tr>
881                 <td> 3 </td>
882                 <td> <code>-wx</code> </td>
883                 <td> write and execute permission </td>
884         </tr> <tr>
885                 <td> 4 </td>
886                 <td> <code>r--</code> </td>
887                 <td> only read permission </td>
888         </tr> <tr>
889                 <td> 5 </td>
890                 <td> <code>r-x</code> </td>
891                 <td> read and execute permission </td>
892         </tr> <tr>
893                 <td> 6 </td>
894                 <td> <code>rw-</code> </td>
895                 <td> read and write permission </td>
896         </tr> <tr>
897                 <td> 7 </td>
898                 <td> <code>rwx</code> </td>
899                 <td> read, write and execute permission </td>
900         </tr>
901 </table>
902
903 <p> The <code>chmod(1)</code> command changes the permission
904 bits of the file identified by the path argument. For example,
905 <code>chmod 600 foo</code> sets the permissions of <code>foo</code> to
906 <code>rw-------</code>. Besides the octal values, <code>chmod(1)</code>
907 supports symbolic notation to address the three classes described
908 above: <code>u</code> selects the user class, <code>g</code> the
909 group class, <code>o</code> the class of other users. The symbolic
910 value <code>a</code> selects all three classes. Moreover, the letters
911 <code>r</code>, <code>w</code> and <code>x</code> are used to set or
912 unset the read, write and execute permission, respectively. The above
913 command is equivalent to <code>chmod u=rw,g=---,o=--- foo</code>. The
914 <code>+</code> and <code>-</code> characters can be specified instead
915 of <code>=</code> to set or unset specific permission bits while
916 leaving the remaining bits unchanged. For example <code>chmod go-rw
917 foo</code> turns off read and write permissions for non-owners. </p>
918
919 <p> Unprivileged users can only change the mode bits of their own
920 files or directories while there is no such restriction for the
921 superuser. </p>
922
923 SUBSECTION(«Hard and Soft Links»)
924
925 <p> Links make it possible to refer to identical files through
926 different paths. They come in two flavors: hard and soft. Both
927 types of links have advantages and disadvantages, and different
928 limitations. We start with hard links because these existed already
929 in the earliest Unix versions. </p>
930
931 <p> A file can have more than one directory entry that points to its
932 inode. If two directory entries point to the same inode, they are
933 said to be <em> hard links</em> of each other. The two entries are
934 equivalent in that they refer to the same file. It is impossible
935 to tell which of the two is the "origin" from which the "link"
936 was created. Hard links are created with the <code>link(2)</code>
937 system call or the <code>ln(1)</code> command. Both take two path
938 arguments, one for the existing file and one for the directory entry
939 to be created. The filesystem maintains in each inode a link counter
940 which keeps track of the number of directory entries which point to the
941 inode. The <code>link(2)</code> system call increases the link count
942 while <code>unlink(2)</code> decrements the link count and removes
943 the directory entry. If the decremented counter remains positive,
944 there is still at least one other directory entry which points to
945 the inode. Hence the file is still accessible through this other
946 directory entry and the file contents must not be released. Otherwise,
947 when the link counter reached zero, the inode and the file contents
948 may be deleted (assuming the file is not in use). </p>
949
950 <p> There are several issues with hard links. For one, hard links
951 can not span filesystems. That is, the two path arguments for
952 <code>link(2)</code> have to refer to files which reside on the
953 same filesystem. Second, it is problematic to create hard links to
954 directories. Early Unix systems allowed this for the superuser,
955 but on Linux the attempt to hard-link a directory always fails.
956 To address the limitations of hard links, <em>soft links</em>, also
957 called <em>symbolic links</em> (or <em>symlinks</em> for short),
958 were introduced. A soft link can be imagined as a special text file
959 containing a single absolute or relative path, the <em>target</em> of
960 the link. For relative paths the implied leading part is the directory
961 that contains the link. A soft link is thus a named reference in
962 the global hierarchy of files. Unlike hard links, the soft link
963 and its target do not need to reside on the same filesystem, and
964 there is a clear distinction between the link and its target. Soft
965 links are created with <code>symlink(2)</code> or by specifying the
966 <code>-s</code> option to the <code>ln(1)</code> command. </p>
967
968 <p> A soft link and its target usually point to different inodes. This
969 raises the following question: Should system calls which receive a
970 path argument that happens to be a soft link operate on the link
971 itself, or should they <em>follow</em> (or <em>dereference</em>)
972 the link and perform the operation on the target? Most system calls
973 follow soft links, but some don't. For example, if the path argument
974 to <code>chdir(2)</code> happens to be a soft link, the link is
975 dereferenced and the working directory is changed to the target of
976 the link instead. The <code>rename(2)</code> system call, however,
977 does not follow soft links and renames the link rather than its
978 target. Other system calls, including <code>open(2)</code>, allow
979 the caller to specify the desired behaviour by passing a flag to the
980 system call. For yet others there is a second version of the system
981 call to control the behaviour. For example, <code>lstat(2)</code> is
982 identical to <code>stat(2)</code>, but does not follow soft links. </p>
983
984 <p> It is possible for a soft link to refer to an invalid path. In
985 fact, <code>ln(1)</code> and <code>symlink(2)</code> do not consider
986 it an error if the target does not exist, and happily create a soft
987 link which points to an invalid path. Such soft links are called
988 <em>dangling</em> or <em>broken</em>. Dangling soft links also occur
989 when the target file is removed or renamed, or after a mount point
990 change. </p>
991
992 <p> Soft links may refer to other soft links. System calls which
993 follow soft links must therefore be prepared to resolve chains of
994 soft links to determine the file to operate on. However, this is not
995 always possible because soft links can easily introduce loops into the
996 hierarchy of files. For example, the commands <code>ln -s foo bar;
997 ln -s bar foo</code> create such a loop. System calls detect this
998 and fail with the <code>Too many levels of symbolic links</code>
999 error when they encounter a loop. </p>
1000
1001 <p> Another issue with both soft and hard links is that there is no
1002 simple way to find all directory entries which point to the same path
1003 (soft links) or inode (hard links). The only way to achieve this is
1004 to traverse the whole hierarchy of files. This may be prohibitive
1005 for large filesystems, and the result is unreliable anyway unless
1006 the filesystems are mounted read-only. </p>
1007
1008 EXERCISES()
1009
1010 <ul>
1011         <li> A path can lack both slashes and components. Give an example
1012         of a path that lacks a slash and another example of a path that has
1013         no components.  </li>
1014
1015         <li> Assume <code>foo</code> is an existing directory. Guess what the
1016         command <code>mv foo bar</code> will do in each of the following cases:
1017         (a) <code>bar</code> does not exist, (b) <code>bar</code> exists and
1018         is a regular file, (c) <code>bar</code> exists and is a directory.
1019         Verify your guess by running the command. </li>
1020
1021         <li> Many programs check if a path is valid and act differently
1022         according to the result. For example, a shell script might
1023         check for the existence of a file with code like <code>if test
1024         -e "$file"; do something_with "$file"; fi</code>. Explain
1025         why this approach is not bullet-proof. How could this be
1026         fixed? </li>
1027
1028         <li> Run <code>touch file-{1..100}</code> to create 100 files. Guess
1029         what the following commands will print. Run each command to confirm.
1030
1031         <ul>
1032                 <li> <code>ls file-</code> </li>
1033                 <li> <code>ls file-*</code> </li>
1034                 <li> <code>ls file-?</code> </li>
1035                 <li> <code>ls file-[1-4]</code> </li>
1036                 <li> <code>ls file-[1,3,5,7,9]*</code> </li>
1037         </ul>
1038         </li>
1039
1040         <li> Find an extended glob pattern for <code>bash(1)</code>
1041         that matches all valid paths whose last component starts with
1042         <code>file-</code>, followed by any number of odd digits (1, 3, 5,
1043         7, or 9). </li>
1044
1045         <li> Point out the flaw in the following shell code: <code>for
1046         f in file-*; do something_with "$f"; done</code>. Hint: Search
1047         <code>bash(1)</code> for "nullglob".
1048
1049         <li> Create a file named <code>-r</code> with <code>echo >
1050         -r</code>. Try to remove the file with <code>rm -r</code> and
1051         discuss why this doesn't work as expected. Find a way to get rid
1052         of the file. Discuss what happens if you run <code>rm *</code> in a
1053         directory which contains a file named <code>-r</code>. </li>
1054
1055         <li> The content of the <code>PATH</code> variable is a
1056         colon-separated list of directories in which the shell looks for
1057         commands to execute. Discuss the dangers of including the current
1058         working directory in this list. </li>
1059
1060         <li> Run <code>id</code> to determine a group <code>G</code> you
1061         belong to but is not your primary group. Consider the following
1062         commands <code>mkdir foo; chgrp $G foo; touch foo/bar</code>. What
1063         is the group ID of <code>foo/bar</code>? Run the same commands, but
1064         insert <code>chmod g+s foo</code> as the second-to-last command. </li>
1065
1066         <li> Run <code>man null</code> and <code>man zero</code> to learn
1067         about the properties of these two character devices. </li>
1068
1069         <li> Assume the modification time stored in the inode of some file
1070         suggests that the file was last modified two years ago. How sure
1071         can you be that the file was never changed since then? Hint: See the
1072         <code>-d</code> option of <code>touch(1)</code>. </li>
1073
1074         <li> Run the following commands <code>echo hello > foo</code>,
1075         <code>cat foo</code>, <code>chmod 600 foo</code>, <code>echo world >>
1076         foo</code>. Check the three timestamps with <code>stat foo</code>
1077         after each command. </li>
1078
1079         <li> Determine the state of the permission bits of your own
1080         home directory by running <code>ls -ld ~</code>. Who can
1081         access its contents? Also look at the permission bits of
1082         other people's home directory. </li>
1083
1084         <li> A file or directory is called <em>world-writeable</em>
1085         if the <code>w</code> bit is set in the <code>others</code>
1086         class of the permission bits. Create a world-writable
1087         directory with <code>mkdir foo; chmod 777 foo</code>
1088         and create a file in the new directory: <code>echo hello
1089         > foo/bar</code>. Is a different user allowed to create
1090         another file there (<code>echo world > foo/baz</code>)? Can
1091         he remove it again (<code>rm foo/baz</code>)? Will he succeed
1092         in removing <code>foo/bar</code> although it is owned by you
1093         and <em>not</em> writable to him? Try the same with the sticky
1094         bit turned on (<code>chmod 1777 foo</code>). </li>
1095
1096         <li> Translate <code>rw-r--r--</code> into octal, and 755 into
1097         <code>rwx</code>-notation. </li>
1098
1099         <li> Create a <a href="#hello_world">hello world script</a>, make it
1100         executable and run it. Create a subdirectory of your home directory
1101         and move the script into this directory. Set the permissions of the
1102         directory to <code>r--------</code>, check whether you still can
1103         list/execute it. Do the same with <code>--x------</code>. </li>
1104
1105         <li> Create a file with <code>echo hello > foo</code>,
1106         create soft and hard links with <code>ln -s foo soft</code>
1107         and <code>ln foo hard</code>. Examine the inode numbers
1108         and link counts using the command <code>stat foo soft
1109         hard</code>. Remove <code>foo</code> and repeat. Try to
1110         access the file content through both links. Guess what
1111         <code>realpath foo soft hard</code> will print. Run the
1112         command to confirm. </li>
1113
1114         <li> Create a dangling symlink with <code>ln -s /nope foo</code>. Would
1115         you expect the commands <code>ls -l foo</code> and <code>cat foo</code>
1116         succeed? Run these commands to verify your guess. </li>
1117
1118         <li> One of the seven Unix file types is symlink. Why is there no
1119         file type for hard links? </li>
1120 </ul>
1121
1122 HOMEWORK(«
1123 How many paths are there that refer to the same file?
1124 », «
1125 Given the path <code>/foo/bar</code>, one may construct different paths
1126 which refer to the same file by inserting any number of <code>/.</code>
1127 or <code>../foo</code> after the first component. For example,
1128 <code>/foo/./bar</code> and <code>/foo/../foo/bar</code> both refer
1129 to the same file. If relative paths have to be taken into account as
1130 well, even more paths can be constructed easily. Hence the answer is:
1131 arbitrary many.
1132
1133 This illustrates the fundamental difference between a path and a
1134 file. Paths can be mapped to files, but not the other way around. In
1135 particular, there is no such thing like "the list of paths which have
1136 changed since yesterday".
1137
1138 The concept of hard- and soft links complicates the situation further.
1139 »)
1140
1141 HOMEWORK(«
1142 Given two paths, how can one tell if they refer to the same file?
1143 », «
1144
1145 Among other information, the metadata record of each file contains the
1146 so-called <em>inode number</em>, which uniquely identifies the file
1147 within the file system that contains the file. Therefore, if both
1148 paths are known to refer to files stored on the same file system,
1149 a comparison of the two inode numbers is sufficient to tell whether
1150 the two paths refer to the same file. The inode number can be obtained
1151 with the command <code>ls -i</code>.
1152
1153 In the general case one additionally has to check that the
1154 two <code>device IDs</code> which identify the underlying file
1155 systems are also identical. Like the inode number, the device ID
1156 is part of the metadata of the file. It can be obtained by running
1157 <code>stat(1)</code>.
1158
1159 »)
1160
1161 HOMEWORK(«
1162 Device nodes come in two flavors: Character and block devices. Explain
1163 the difference between the two device flavors.
1164 »)
1165
1166 HOMEWORK(«
1167
1168 <ul>
1169         <li> Nine of the 12 mode bits of each file are the permission
1170         bits. The remaining three are the <em>sticky</em>, <em>setuid</em>
1171         and <em>setgid</em> bits. Explain the purpose of each. </li>
1172
1173         <li> Run <code>find /usr/bin/ -perm -2000 -ls</code> to see all SUID
1174         executables in <code>/usr/bin</code>. Discuss why those programs have
1175         the SUID bit set. </li>
1176 </ul>
1177
1178 »)
1179
1180 HOMEWORK(«
1181 How many possible permission modes exist for a file or directory on
1182 a Unix System?
1183 », «
1184 There are nine permission bits that can be turned on and off
1185 independently. Hence we have 2^9=512 possibilities. When taking into
1186 account the three special bits (sticky, setuid, setgid), the number
1187 increases to 2^12=4096.
1188 »)
1189
1190 HOMEWORK(«
1191 Explain each command of the <a href="«#»symlink_madness">script</a>
1192 below. Show the arrangement of all files and links in a figure,
1193 drawing a directory as a circle and a file as a square.  How many
1194 different paths exist for the file <code> a</code>? Discuss whether
1195 the question "What's the path of a given file?" makes sense.
1196
1197 », «
1198
1199 <div>
1200 <svg
1201         width="150" height="125"
1202         xmlns="http://www.w3.org/2000/svg"
1203         xmlns:xlink="http://www.w3.org/1999/xlink"
1204 >
1205         <marker
1206                 id="slm_arrow"
1207                 viewBox="0 0 10 10" refX="5" refY="5"
1208                 markerWidth="4" markerHeight="4"
1209                 orient="auto-start-reverse">
1210                 <path d="M 0 0 L 10 5 L 0 10 z" />
1211         </marker>
1212         <circle
1213                 fill="#ccc"
1214                 stroke-width="1"
1215                 stroke="black"
1216                 r=20
1217                 cx=51
1218                 cy=21
1219         />
1220         <text
1221                 x="51"
1222                 y="21"
1223                 stroke="black"
1224                 text-anchor="middle"
1225                 dy="0.3em"
1226         >foo</text>
1227         <rect
1228                 fill="#ccc"
1229                 stroke-width="1"
1230                 stroke="black"
1231                 x=1
1232                 y=81
1233                 width="40"
1234                 height="40"
1235                 rx="5"
1236         />
1237         <text
1238                 x="21"
1239                 y="101"
1240                 stroke="black"
1241                 text-anchor="middle"
1242                 dy="0.3em"
1243         >a</text>
1244         <ellipse
1245                 cx=81
1246                 cy=101
1247                 rx=30
1248                 ry=20
1249                 fill="#ccc"
1250                 stroke-width="1"
1251                 stroke="black"
1252         />
1253         <text
1254                 x="81"
1255                 y="101"
1256                 stroke="black"
1257                 text-anchor="middle"
1258                 dy="0.3em"
1259         >testdir</text>
1260         <line
1261                 stroke="black"
1262                 stroke-width="1"
1263                 x1="41"
1264                 y1="45"
1265                 x2="24"
1266                 y2="75"
1267         />
1268         <line
1269                 stroke="black"
1270                 stroke-width="1"
1271                 x1="61"
1272                 y1="45"
1273                 x2="77"
1274                 y2="75"
1275         />
1276         <path
1277                 d="
1278                         M 118,101
1279                         C 150,90 150,30 80,20
1280                 "
1281                 stroke-width="2"
1282                 stroke="black"
1283                 fill="none"
1284                 marker-end="url(#slm_arrow)"
1285         />
1286 </svg>
1287 </div>
1288
1289 Since <code> foo/a</code>, <code> foo/testdir/a</code>, <code>
1290 foo/testdir/testdir/a </code> etc. all refer to the same file, there
1291 are infinitely many paths for the file <code> a</code>. Hence the
1292 question makes no sense: There is no such thing as <em> the </em>
1293 path to a file.
1294
1295 »)
1296
1297 HOMEWORK(«
1298
1299 Recall that the path component <code>..</code> refers to the
1300 parent directory. Give an example of a path to a directory where
1301 "parent directory" and "directory identified by the path obtained by
1302 removing the last path component" are different. Which of the two
1303 interpretations of <code>..</code> does bash apply when you type
1304 <code>cd ..</code> at the bash prompt?
1305
1306 »)
1307
1308 HOMEWORK(«
1309
1310 Is it possible to choose among all possible paths which refer to the
1311 same file a <em>canonical</em> path? That is, a shortest (counting
1312 characters) absolute path which does not contain any soft links?
1313
1314 », «
1315
1316 <p> The POSIX standard requires each Unix system library to provide
1317 the <code>realpath()</code> function which performs the following
1318 substitutions on the given path: First, the path to the current
1319 working directory is prepended if the given path is relative
1320 (does not begin with a slash). Second, symbolic links are replaced
1321 by their targets. Third, any occurrences of <code>/.</code> and
1322 <code>foo/..</code> are removed. The thusly transformed path is
1323 returned by the function as the canonical path. </p>
1324
1325 <p> Although each path can be canonicalized in this way, not all paths
1326 which refer to the same file give rise to the same canonical path. For
1327 example, <code>/tmp/foo</code> and <code>/tmp/bar</code> could refer
1328 to regular files which are hard links of each other. In this case the
1329 paths refer to the same file, yet the paths are different and already
1330 canonicalized. The same can happen when a file system (or a subtree
1331 of it) is <em>bind mounted</em>. That is, the file system tree is
1332 visible at two or more locations in the global directory tree. </p>
1333
1334 The message of this exercise is to convince the reader that it is
1335 incorrect to assume that two files are different because their paths
1336 are different.
1337
1338 »)
1339
1340 SECTION(«Processes»)
1341
1342 <p> A <em>program</em> consists of instructions and data stored in
1343 a regular file. A <em> user process</em> is an instance of a running
1344 program. This is in contrast to <em>kernel processes</em> which are
1345 created directly by the kernel and have no relationship to executable
1346 files. Since we shall only be concerned with user processes, we will
1347 refer to these as "processes" from now on. In this section we'll see
1348 how processes are created and removed. We will then take a closer look
1349 at the enviroment of a process and discuss how processes communicate
1350 with each other. </p>
1351
1352 SUBSECTION(«Process Tree, Zombies and Orphans»)
1353
1354 <p> When the system boots, there is only one process, the
1355 <em>init</em> process, which is created by the kernel at the end
1356 of the boot sequence by executing <code>/sbin/init</code>. All
1357 other processess are created from existing processes by means of
1358 the <code>fork(2)</code> system call. The process which called
1359 <code>fork(2)</code> is said to be the <em>parent</em> of the newly
1360 created <em>child</em>. After <code>fork(2)</code> returns, both
1361 parent and child are executing independently of each other. Both
1362 processes may call <code>fork(2)</code> again to create further
1363 processes. This gives rise to a tree structure where the processes
1364 are the nodes of the tree with init being the root node. The edges
1365 of the tree describe the parent-child relationships. </p>
1366
1367 <p> If there are more processes than CPUs, not all processes can
1368 run simultaneously. It is the mission of the kernel's <em>task
1369 scheduler</em> to assign processes to CPUs and to perform <em>context
1370 switches</em>. That is, to take away the CPU from a running process
1371 in order to give another process the chance to run. The scheduler
1372 has to choose the duration of each process' time slice and it must
1373 pick the process to switch to when the time slice of the current
1374 process has expired or the process gives up the CPU voluntarily, for
1375 example because it is waiting for an I/O operation to complete. This
1376 is a non-trivial task at least for modern multi-CPU systems with
1377 <em>non-uniform memory access</em> (NUMA) where the memory access times
1378 depend on the memory location and the processor core. Things don't
1379 get easier if the CPU clock speed can vary and/or scheduling must be
1380 power-aware to optimize battery time. To make good decisions, some
1381 information has to be provided by the processes or by a system-wide
1382 policy. One elementary way to prioritize certain processes over others
1383 is via <em>nice levels</em> which we shall discuss below. </p>
1384
1385 <p> The normal way for a process to terminate is to call
1386 <code>exit(3)</code> after it has done its work. This function
1387 transfers an integer value, the <em>exit status</em>, to the
1388 kernel. The exit status can only be retrieved by the parent of
1389 the terminating process. To illustrate this concept, imagine an
1390 interactive shell which creates one child each time the user enters
1391 a command. The children are short living while the parent, the shell,
1392 stays around for much longer. During command execution the parent needs
1393 to wait for its child to terminate. It may then want to tell whether
1394 the child has terminated successfully. To achieve this, the parent
1395 calls one of the <em>wait</em> system calls (<code>wait(2)</code>,
1396 <code>waitpid(2)</code>, <code>waitid(2)</code>) which block until the
1397 child has terminated, then return the child's exit status. After the
1398 child called <code>exit(3)</code> but before the parent has called
1399 one of the wait functions, the kernel needs to keep at least the
1400 exit status (and possibly further information) about the terminated
1401 child. During this time window the child has already terminated but
1402 a part of it still exists in kernel memory. Processes in this state
1403 are aptly called <em>zombies</em>. </p>
1404
1405 <p> Unlike in the shell scenario outlined above, a process might well
1406 have any number of children at the time it terminates. Its children
1407 then become <em>orphans</em> as they lose their parent. The kernel
1408 cannot simply remove the terminated process from the process tree
1409 because this would disconnect its orphaned children from the other
1410 processes in the tree, destroying the tree structure. To avoid this,
1411 orphans are <em>reparented to init</em>, that is, made children
1412 of the init process. This works because the init process never
1413 terminates. </p>
1414
1415 <p> There are several programs which show information about
1416 processes. The POSIX <code>ps(1)</code> command prints a list of
1417 processes. It has many options that control which processes are
1418 shown and how the output is formatted. Similar programs which are not
1419 covered by POSIX are <code>pstree(1)</code>, <code>top(1)</code> and
1420 <code>htop(1)</code>. The former shows the tree structure while the
1421 latter two provide a dynamic real-time view of the process tree. The
1422 exercises of this section invite the reader to become familiar with
1423 these essential programs. </p>
1424
1425 SUBSECTION(«File Execution»)
1426
1427 <p> When a process calls <code>fork(2)</code>, the newly created
1428 child process starts out as a copy of the calling process. However,
1429 the reason to create a new process is usually to let the child do
1430 something different than the parent. Therefore, <code>fork(2)</code>
1431 is often followed by a second system call which replaces the child
1432 process with a different program. There are several similar system
1433 calls which do this, with slight semantic differences. We refer to
1434 this family of system calls as the <em>exec system calls</em>. </p>
1435
1436 <p> All exec system calls receive a path argument from which they
1437 determine an executable file that contains the program to run. Linux
1438 and BSD store executables in <em>Executable and Linkable Format</em>
1439 (ELF). Executables are typically linked <em>dynamically</em>.
1440 That is, the dependent libraries (at least libc, but possibly many
1441 more) are loaded at runtime from separate files. This is in contrast
1442 to <em>static linking</em> which includes all dependencies in the
1443 executable, making the executable self-contained but also larger
1444 and harder to maintain. Regardless of the type of linking, when the
1445 program is loaded, it completely replaces the previously running
1446 program. Note that there can be more than one process at the same
1447 time which executes the same program. </p>
1448
1449 <p> Files in ELF format are called <em>native</em> executables because
1450 they contain machine instructions which can be executed directly
1451 by the CPU. Another type of executables are <em>scripts</em>,
1452 also known as <em>interpreter files</em>. Scripts are text files
1453 which start with the <em>shebang</em> (<code>#!</code>). They can
1454 not run directly but have to be <em>interpreted</em> at runtime
1455 by another program, the <em>interpreter</em>. Nevertheless, it is
1456 possible to execute a script as if it were a native executable:
1457 by passing the path to one of the exec system calls or by typing
1458 the path at the shell prompt. The exec system call recognizes that
1459 the given file is a script by investigating the first line, which
1460 contains the path to the interpreter after the shebang, optionally
1461 followed by options to the interpreter. The kernel then executes the
1462 interpreter rather than the script, passing the path to the script as
1463 an argument. For example, if <code>/foo/bar</code> is being executed,
1464 and the first line of this file is <code>#!/bin/sh</code>, the kernel
1465 executes <code>/bin/sh /foo/bar</code> instead. Popular interpreters
1466 besides <code>/bin/sh</code> include <code>/bin/bash</code>,
1467 <code>/usr/bin/perl</code>, <code>/usr/bin/python</code> and
1468 <code>/usr/bin/awk</code>. </p>
1469
1470 SUBSECTION(«File Descriptions and File Descriptors»)
1471
1472 <p> The kernel must always be aware of the set of all objects which are
1473 currently in use. This set is often called the <em>system-wide table
1474 of open files</em> although not all entries refer to files. In fact, an
1475 entry may refer to any object that supports I/O operations, for example
1476 a network socket. Each entry is called a <em>file description</em>,
1477 which is a somewhat unfortunate term that was coined by POSIX. A
1478 file description records information about the object itself as well
1479 as the current state of the reference, including the file offset,
1480 if applicable, and the <em>status flags</em> which affect how future
1481 I/O operations are going to be performed through this reference. </p>
1482
1483 <p> The kernel maintains for each process an array of pointers to file
1484 descriptions. Each such pointer is a <em>file descriptor</em>. Unlike
1485 files and file descriptions, a file descriptor always corresponds
1486 to a process and is identified by a non-negative number, the index
1487 into the pointer array of that process. This index is returned by
1488 system calls like <code>open(2)</code> or <code>socket(2)</code>.
1489 As far as user space programs are concerned, a file descriptor is
1490 synonymous with this integer. It can be regarded as an abstract
1491 <em>handle</em> that must be supplied to subsequent I/O operations
1492 like <code>read(2)</code> or <code>write(2)</code> to tell the system
1493 call the target object of the operation. </p>
1494
1495 <p> The shell automatically creates three file descriptors for each
1496 process which are identified by the integers 0, 1 and 2. They are
1497 called <em>stdin</em>, <em>stdout</em>, and <em>stderr</em>, which is
1498 short for <em>standard input/output/error</em>. It is possible, and in
1499 fact common, that all three file descriptors point to the same file
1500 description: the terminal device. Many command line tools read their
1501 input from stdin, write normal output to stdout, and error messages
1502 to stderr. For example, when the POSIX command <code>cat(1)</code>
1503 is invoked with no arguments, it reads data from stdin and writes
1504 the same data to stdout. </p>
1505
1506 SUBSECTION(«Signals»)
1507
1508 <p> Signals are another ancient Unix concept that dates back to the
1509 early 1970s and was standardized in POSIX long ago. This concept
1510 facilitates a rudimentary form of <em>inter process communication</em>
1511 (IPC) between unrelated processes. Signals can be regarded as software
1512 interrupts that transmit a notification event from the sending process
1513 to the target process. The event is sent <em>asynchronously</em>,
1514 meaning that the interruption can happen at any location of the code
1515 flow. </p>
1516
1517 <p> It is fair to say that most non-trivial programs, including
1518 scripts, have to deal with signals. All major scripting languages
1519 (bash, python, perl, ruby, etc.) provide an API for signal
1520 handling. The interpreter of the scripting language ends up calling
1521 the POSIX system functions, so we will only look at these. </p>
1522
1523 <p> Signals are identified by name or by a numerical ID. For example,
1524 <code>SIGINT</code> (interrupt from keyboard) is the name for signal
1525 number 2. POSIX defines 31 <em>standard signals</em> plus at least
1526 eight <em>real-time signals</em>. The standard signals can be
1527 subdivided according to the origin of the signal as follows. </p>
1528
1529 <dl>
1530         <dt> hardware related signals </dt>
1531
1532         <dd> These signals originate from <em>hardware traps</em> that force
1533         the CPU back into kernel mode. The kernel responds to the trap by
1534         generating a signal for the process that caused the trap. For example,
1535         a division by zero in a user space program triggers a hardware trap
1536         in the <em>floating point unit</em> (FPU) of the CPU. The kernel
1537         then generates the <code>SIGFPE</code> (floating-point exception)
1538         signal for the process. Another example for a signal that originates
1539         from a hardware trap is <code>SIGSEGV</code> (segmentation fault)
1540         which occurs when a process attempts to reference a memory address
1541         that has not been mapped (i.e., marked as valid) by the <em>memory
1542         management unit</em> (MMU) of the CPU. </dd>
1543
1544         <dt> kernel generated signals </dt>
1545
1546         <dd> Signals which originate from the kernel rather than from
1547         hardware. One example is <code>SIGCHLD</code> (child terminated),
1548         which is sent to the parent process when one of its child processes
1549         terminates. Another example is <code>SIGWINCH</code> (window resize),
1550         which is generated when the geometry of the controlling terminal of
1551         a process changes. </dd>
1552
1553         <dt> user-space generated signals </dt>
1554
1555         <dd> These signals can only originate from user space when a process,
1556         for example <code>kill(1)</code>, calls <code>raise(2)</code>
1557         or <code>kill(2)</code> to instruct the kernel to generate a
1558         signal. Examples are <code>SIGTERM</code>, which issues a termination
1559         request, and <code>SIGUSR1</code> and <code>SIGUSR2</code> which are
1560         reserved for use by application programs. </dd>
1561 </dl>
1562
1563 The following signals are used frequently and deserve to the described
1564 explicitly. We refer to <code>signal(7)</code> for the full list of
1565 signals and their semantics.
1566
1567 <dl>
1568         <dt> <code>SIGINT, SIGTERM</code> and <code>SIGKILL</code> </dt>
1569
1570         <dd> All three signals terminate the process by default.
1571         <code>SIGINT</code> is generated for the <em>foreground processes</em>
1572         when the <em>interrupt character</em> (CTRL+C) is pressed in a
1573         terminal. For example, if CTRL+C is pressed while the shell pipeline
1574         <code>find | wc </code> is executing, <code>SIGINT</code> is sent
1575         to both processes of the pipeline. <code>SIGTERM</code> is the
1576         default signal for the <code>kill(1)</code> command. It requests
1577         the target process to run its shutdown procedure, if any, then
1578         terminate. <code>SIGKILL</code> instructs the kernel to terminate the
1579         target process immediately, without giving the process the chance to
1580         clean up. This signal can originate from a process or from the kernel
1581         in response to running out of memory. To keep the system working, the
1582         kernel invokes the infamous <em>out of memory killer</em> (OOM killer)
1583         which terminates one memory-hungry process to free some memory. </dd>
1584
1585         <dt> <code>SIGSTOP</code>, <code>SIGTSTP</code> and <code>SIGCONT</code> </dt>
1586
1587         <dd> <code>SIGSTOP</code> instructs the task scheduler of the kernel to
1588         no longer assign any CPU time to the target process until the process
1589         is woken up by a subsequent <code>SIGCONT</code>. <code>SIGTSTP</code>
1590         (stop typed at terminal) stops all foreground processes of a terminal
1591         session. It is generated when the <em>stop character</em> (CTRL+Z)
1592         is pressed in a terminal. </dd>
1593 </dl>
1594
1595 <p> Processes may set the <em>signal disposition</em> of most signals
1596 to control what happens when the signal arrives. When no disposition
1597 has been set, the signal is left at its <em>default disposition</em> so
1598 that the <em>default action</em> is performed to deliver the signal.
1599 For most signals the default action is to terminate the process,
1600 but for others the default action is to <em>ignore</em> the signal.
1601 If the signal is neither ignored nor left at its default disposition,
1602 it is said to be <em>caught</em> by the process. To catch a signal the
1603 process must tell the kernel the address of a function, the <em>signal
1604 handler</em>, to call in order to deliver the signal. The set of
1605 signal dispositions of a process can thus be imagined as an array
1606 of function pointers with one pointer per possible signal. If the
1607 process catches the signal, the pointer points to the corresponding
1608 signal handler. A NULL pointer represents a signal that was left at
1609 its default disposition while the special value <code>SIG_IGN</code>
1610 indicates that the process explicitly asked to ignore this signal. </p>
1611
1612 <p> Signals can also be <em>blocked</em> and <em>unblocked</em>. When
1613 a signal is generated for a process that has it blocked, it remains
1614 <em>pending</em>. Pending signals cause no action as long as the
1615 signal remains blocked but the action will be performed once the
1616 signal gets unblocked. <code>SIGKILL</code> and <code>SIGSTOP</code>
1617 can not be caught, blocked, or ignored. </p>
1618
1619 <p> Real-time signals are similar to <code>SIGUSR1</code> and
1620 <code>SIGUSR2</code> in that they have no predefined meaning but
1621 can be used for any purpose. However, they have different semantics
1622 than the standard signals and support additional features. Most
1623 importantly, real-time signals are <em>queued</em>, meaning that in
1624 contrast to standard signals the same real-time signal can be pending
1625 multiple times. Also, the sending process may pass an <em>accompanying
1626 value</em> along with the signal. The target process can obtain this
1627 value from its signal handler along with additional information like
1628 the PID and the UID of the process that sent the signal. </p>
1629
1630 <p> Some system calls including <code>read(2)</code> and
1631 <code>write(2)</code> may block for an indefinite time. For
1632 example, reading from a network socket blocks until there is data
1633 available. What should happen when a signal arrives while the process
1634 is blocked in a system call? There are two reasonable answers: Either
1635 the system call is <em>restarted</em>, or the call fails with the
1636 <code>Interrupted system call</code> error. Unfortunately, different
1637 flavors of Unix handle this case differently by default. However,
1638 applications may request either behaviour by setting or clearing the
1639 <code>SA_RESTART</code> flag on a per-signal basis. </p>
1640
1641 SUBSECTION(«Environment of a Process»)
1642
1643 <p> Now that we have a rough understanding of processes we look
1644 closer at the information the kernel maintains for each process. We
1645 already discussed the array of file descriptors and the array of
1646 signal dispositions. Clearly both are process specific properties.
1647 As we shall see, there is much more what constitutes the environment
1648 of a process. </p>
1649
1650 <p> Each process is identified by a unique <em>process ID</em>
1651 (PID), which is a positive integer. The <code>init</code> process is
1652 identified by PID 1. PIDs are assigned in ascending order, but are
1653 usually restricted to the range 1..32767. After this many processes
1654 have been created, PIDs wrap and unused PIDs are recycled for new
1655 processes. Thus, on a busy system on which processes are created and
1656 terminated frequently, the same PID is assigned to multiple processes
1657 over time. </p>
1658
1659 <p> Not all processes call <code>fork(2)</code> to create a child
1660 process, but each process except the init process has a unique
1661 parent. As described before, this is either the "real" parent (the
1662 process which created the process earlier) or the init process that
1663 "adopted" the orphaned process in case the real parent terminated
1664 before the child. The process ID of the parent (PPID) is thus
1665 well-defined. A process can obtain its PID and PPID with the
1666 <code>getpid(2)</code> and <code>getppid(2)</code> system calls. </p>
1667
1668 <p> Each process runs on behalf of a user (possibly the superuser)
1669 which is identified by its <em>user ID</em> (UID) and belongs to
1670 one or more groups, identified by one or more <em>group IDs</em>
1671 (GIDs). The superuser is identified by UID zero. When we talked
1672 about the permission bits of files and directories, we said that
1673 suitable permissions are needed for system calls which operate on
1674 files (<code>open(2)</code>, <code>stat(2)</code>, etc.). A more
1675 precise statement is that the <em>process</em> which calls, say,
1676 <code>open(2)</code> needs to have these permissions. To decide this,
1677 the kernel needs to take into account the UID and GIDs of the process
1678 that called <code>open(2)</code>, the UID and the GID stored in the
1679 inode of the file that is being opened, and the permission bits of
1680 this file. The UID is also taken into account for <code>kill(2)</code>
1681 because unprivileged processes (non-zero UID) can only send signals
1682 to processes which run on behalf of the same user while the superuser
1683 may target any process. </p>
1684
1685 <p> Each process has a <em>current working directory</em> (CWD)
1686 associated with it. When the user logs in, the CWD of the login shell
1687 process is set to his <em>home directory</em>, which should always
1688 exist and have the read, write and execute permission bits set for
1689 the user. The CWD can later be changed with <code>chdir(2)</code>
1690 and be retrieved with <code>getcwd(3)</code>. The CWD is used as the
1691 starting point for path searches for relative paths. It affects most
1692 system calls which receive a path argument. For example, if the CWD
1693 is <code>/foo/bar</code> and the relative path <code>baz/qux</code>
1694 is passed to <code>open(2)</code>, the kernel will attempt to open
1695 the file which is identified by <code>/foo/bar/baz/qux</code>. </p>
1696
1697 <p> Many programs accept arguments to control their behavior.
1698 In addition to the path to the program that is to be executed,
1699 all variants of the exec system calls receive an array of arguments
1700 called the <em>argument vector</em>. For example, when the command
1701 <code>ls -l foo</code> is executed, the argument vector contains
1702 the two strings <code>"-l"</code> and <code>"foo"</code>. Note that
1703 the argument vector is not part of the program but is tied to the
1704 process. It is passed to the main function at startup so that the
1705 program may evaluate it and act accordingly. </p>
1706
1707 <p> Another way to pass information to a program is via <em>environment
1708 variables</em>. Environment variables are strings of the form
1709 <code>name=value</code>. POSIX describes the API to maintain the
1710 environment variables of a process. Environment variables are set
1711 with <code>setenv(3)</code> or <code>putenv(3)</code>, the value of a
1712 variable can be retrieved with <code>getenv(3)</code>, and a variable
1713 and its value can be deleted with <code>unsetenv(3)</code>. The set of
1714 environment variables is sometimes called the <em>environment</em>
1715 of the process, although we use this term in a broader sense to
1716 describe the entirety of all metadata maintained by the kernel about
1717 the process, including but not limited to environment variables. </p>
1718
1719 <p> Each process also has about a dozen <em>resource limits</em>
1720 that can be set and queried with the POSIX <code>setrlimit(2)</code>
1721 and <code>getrlimit(2)</code> functions. Each limit controls a
1722 different aspect. For example, <code>RLIMIT_CPU</code> limits the
1723 CPU time the process is allowed to use and <code>RLIMIT_NOFILE</code>
1724 controls how many open files it may have at a time. For each resource
1725 there is a <em>soft</em> and a <em>hard</em> limit. The kernel
1726 enforces the value stored as the soft limit. This value may be set
1727 by an unprivileged process to any value between zero and the hard
1728 limit. Unprivileged processes may also reduce (but not increase) their
1729 hard limits. Once a hard limit is reduced, it can not be increased
1730 any more. For <code>RLIMIT_CPU</code> a special convention applies:
1731 If the soft limit is reached, the kernel sends <code>SIGXCPU</code>
1732 (CPU time limit exceeded) to notify the process about this fact so
1733 that it can terminate orderly (e.g., remove temporary files). When
1734 the hard limit is reached, the kernel terminates the process as if
1735 it received <code>SIGKILL</code>. </p>
1736
1737 <p> The <em>nice level</em> of a process provides a hint for
1738 the task scheduler to give the process a lower or higher priority
1739 relative to other processes. Nice levels range between -20 and 19. A
1740 high nice level means that the process wants to be nice to other
1741 processes, that is, should run with reduced priority. Low nice levels
1742 indicate important processes that should be prioritized over other
1743 processes. The default nice level is zero. Unprivileged users may
1744 set the nice level of new processes with the <code>nice(1)</code>
1745 command to any non-negative value. They can also increase the nice
1746 level of their existing processes with <code>renice(1)</code>, but
1747 never decrease it. The superuser, however, may set the nice level
1748 of any process to an arbitrary value in the valid range. </p>
1749
1750 <p> The bulk of the properties discussed so far are inherited by the
1751 child after a <code>fork(2)</code>. Specifically, the child gets the
1752 same array of file descriptors and signal dispositions as its parent,
1753 runs on behalf of the same user, has the same working directory,
1754 the same resource limits and nice level, and also the same set
1755 of environment variables with identical values. The PID and PPID,
1756 however, are different of course. </p>
1757
1758 <p> After a process has called an exec function to replace itself with
1759 a new program, its signal handlers no longer exist because they were
1760 part of the program code which has been replaced. Therefore the exec
1761 system calls reset the disposition of all signals that were caught to
1762 the default disposition. Signals that were being ignored keep being
1763 ignored, however. </p>
1764
1765 SUBSECTION(«The Process Filesystem»)
1766
1767 <p> Although not covered by POSIX, at least Linux, NetBSD and FreeBSD
1768 provide information about processes via the <em>process filesystem</em>
1769 (procfs), which is usually mounted on <code>/proc</code>. The process
1770 filesystem is a <em>pseudo-filesystem</em>, i.e., it has no underlying
1771 storage device. Files and directories are faked by the kernel as they
1772 are accessed. Each process is represented by a numerical subdirectory
1773 of <code>/proc</code> which is named by the PID. For example,
1774 <code>/proc/1</code> represents the init process. The aforementioned
1775 process utilities (<code>ps(1)</code>, <code>top(1)</code>, etc.) read
1776 the contents of the process filesystem in order to do their job. <p>
1777
1778 <p> Each <code>/proc/[pid]</code> directory contains the same set
1779 of files although this set is different between Unixes. These files
1780 expose much of the environment of the process to user space. The Linux
1781 procfs implementation provides text files named <code>environ</code>
1782 and <code>limits</code> which contain the current environment and
1783 the resource limits of the process, respectively. Moreover, the
1784 file descriptor array of each process is exposed in the files of
1785 the <code>/proc/[pid]/fd</code> directory. Linux and NetBSD (but not
1786 FreeBSD) also provide a <code>cwd</code> soft link which points to
1787 the current working directory of the process. </p>
1788
1789 SUBSECTION(«Pipes and Redirections»)
1790
1791 <p> The <code>pipe(2)</code> system call takes no arguments and
1792 creates two file descriptors for the calling process which are tied
1793 together as a unidirectional first in, first out data channel. One
1794 file descriptor is the <em>read end</em> of the pipe, the other is
1795 the <em>write end</em>. Data written to the write end is buffered by
1796 the kernel and can be obtained by reading from the read end. </p>
1797
1798 <p> One application of pipes is communication between
1799 related processes. A process first creates a pipe, then calls
1800 <code>fork(2)</code> to create a child process. The child inherits
1801 a copy of both pipe file descriptors. Hence the parent process can
1802 communicate with the child by writing a message to the write end of
1803 the pipe for the child to read. </p>
1804
1805 <p> This approach depends on file descriptor inheritance across
1806 <code>fork(2)</code>, so it does not work in the situation
1807 where neither process is an ancestor of the other. Files of
1808 type <em>fifo</em> (named pipes) overcome this restriction. To
1809 establish a connection between two <em>unrelated</em> processes,
1810 both processes call <code>open(2)</code> to obtain a file
1811 descriptor which is associated with the fifo. One process passes
1812 the <code>O_WRONLY</code> flag to open the file for writing while
1813 the other passes <code>O_RDONLY</code> to open it for reading. The
1814 two processes may then communicate in the same way as with the
1815 <code>pipe(2)/fork(2)</code> approach. </p>
1816
1817 <p> The POSIX <code>dup(2)</code> and <code>dup2(2)</code> system
1818 calls allow a process to manipulate the entries of its file descriptor
1819 array. In particular the standard file descriptors 0, 1, and 2 can be
1820 replaced. By doing so before performing an exec system call, it can
1821 be arranged that the replacement program starts with, say, its stdout
1822 file descriptor be redirected to the write end of a pipe. Note that
1823 the replacement program does not need any modifications for this to
1824 work, and might not even be aware of the fact that it is not writing
1825 its output to the terminal as usual. </p>
1826
1827 <p> Shells employ this technique to implement the <code>|</code>
1828 operator which "pipes" the output of one command "into" another
1829 command. For example, the pipeline <code>ls | wc</code> works
1830 as follows: First the shell creates a pipe, then it calls
1831 <code>fork(2)</code> twice to create two processes which both
1832 get a copy of the two pipe file descriptors. The first process
1833 replaces its stdout file descriptor with the write end of the
1834 pipe and performs an exec system call to replace itself with the
1835 <code>ls(1)</code> program. The second process replaces its stdin
1836 file descriptor with the read end of the pipe and replaces itself
1837 with <code>wc(1)</code>. Since <code>ls(1)</code> writes to stdout
1838 and <code>wc(1)</code> reads from stdin, <code>wc(1)</code> processes
1839 the output of <code>ls(1)</code>. </p>
1840
1841 SUBSECTION(«Stdio»)
1842
1843 <p> The POSIX standard requires a compliant Unix system to provide
1844 a collection of functions that let applications perform input and
1845 output by means of operations on <em>streams</em>. This programming
1846 interface, known as <em>stdio</em> for <em>standard input/output</em>,
1847 is part of every Unix system since 1979. Every program which contains
1848 a <code>printf(3)</code> statement relies on stdio. </p>
1849
1850 <p> The stdio functions are implemented as part of libc on top of the
1851 <code>open(2)</code>, <code>read(2)</code> and <code>write(2)</code>
1852 system calls which are implemented in the kernel. Roughly speaking,
1853 stdio replaces the file descriptor API by a more abstract API
1854 which centers around streams. A stream is an opaque data structure
1855 which comprises a file descriptor and an associated data buffer for
1856 I/O. Each program has three predefined streams which correspond to
1857 the three standard file descriptors (stdin, stdout and stderr). The
1858 stdio API contains well over 50 functions to create and maintain
1859 streams and to perform I/O on streams. These functions take care of
1860 the characteristics of the underlying file description. For example,
1861 they automatically try to select the optimal I/O buffer size. </p>
1862
1863 <p> Many applications rely on stdio because of convenience. For
1864 one, the buffers for <code>read(2)</code> and <code>write(2)</code>
1865 must be allocated and freed explicitly by the application, and care
1866 must be taken to not overflow these buffers. With stdio, this task
1867 is done by the stdio library. Second, <em>formatted</em> I/O is
1868 much easier to do with the stdio functions because the programmer
1869 only has to provide a suitable <em>format string</em> to convert
1870 between the machine representation and the textual representation of
1871 numbers. For example, by passing the format string <code>"%f"</code>
1872 to <code>scanf(3)</code>, the programmer tells the stdio library to
1873 read a floating point number stored in textual representation from the
1874 specified stream, convert it to machine representation and store it
1875 in the given variable. The <code>fprintf(3)</code> function works the
1876 other way round: the value is converted from machine representation
1877 to text, and this text is written to the stream. Both functions can
1878 deal with various formats, like scientific notation for floating
1879 point numbers (e.g., 0.42E-23). With stdio it is easy to customize
1880 the formatted output, for example add leading zeros or select the
1881 number of decimal digits in the textual representation of a floating
1882 point number. </p>
1883
1884 <p> Another reason why many programs rely on stdio is that it performs
1885 <em>buffered</em> I/O. With buffered I/O not each read/write operation
1886 results in a system call. Instead, data read from or written to the
1887 stream is first stored in the user space buffer that is associated
1888 with the stream. This is a performance improvement for applications
1889 which perform many small I/O operations because every system call
1890 incurs some overhead. Buffers may be <em>flushed</em> explicitly by
1891 calling <code>fflush(3)</code>, or implicitly by the stdio library. The
1892 criteria which cause an implicit flush depend on the <em>buffering
1893 type</em> of the stream. Three buffering types exist. </p>
1894
1895 <dl>
1896         <dt> unbuffered </dt>
1897
1898         <dd> The stdio library does not buffer any reads or writes. Instead,
1899         each I/O operation results in a <code>read(2)</code> or
1900         <code>write(2)</code> system call. By default the stderr stream is
1901         unbuffered to display error messages as quickly as possible. </dd>
1902
1903         <dt> line buffered </dt>
1904
1905         <dd> System calls are performed when a newline character is
1906         encountered. This buffering type applies by default to interactive
1907         sessions where the file descriptor of the stream refers to a terminal
1908         device (as determined by <code>isatty(3)</code>). </dd>
1909
1910         <dt> fully buffered </dt>
1911
1912         <dd> I/O takes place only if the buffer of the stream is empty/full. By
1913         default, if the file descriptor refers to a regular file, the
1914         stream is fully buffered. POSIX requires that stderr is never fully
1915         buffered. </dd>
1916 </dl>
1917
1918 <p> The exercises on stdio focus on the three different buffering
1919 types because this is a common source of confusion. </p>
1920
1921 SUBSECTION(«The Virtual Address Space of a Process»)
1922
1923 <p> Isolation refers to the concept that each process gets its own
1924 <em>virtual address space</em>. A rough understanding of the memory
1925 management system and the layout of the virtual address space of
1926 a process helps to locate the source of common problems like the
1927 infamous <code>segmentation fault</code> error, and to realize that
1928 putatively simple questions such as "how much memory is my process
1929 currently using?" are in fact not simple at all, and need to be made
1930 more precise before they can be answered. </p>
1931
1932 <div>
1933
1934 define(«vas_width», «200»)
1935 define(«vas_height», «300»)
1936 define(«vas_vmem_left_margin», «5»)
1937 define(«vas_vmem_top_margin», «5»)
1938 define(«vas_mem_width», «20»)
1939 define(«vas_gap_width», «30»)
1940 define(«vas_vmem_height», «140»)
1941 define(«vas_vmem_color», «#34b»)
1942 define(«vas_pmem_height», «100»)
1943 define(«vas_pmem_color», «#7e5»)
1944 define(«vas_vmem_unmapped_color», «#a22»)
1945 define(«vas_vmem_swapped_color», «yellow»)
1946 define(«vas_pmem_unavail_color», «orange»)
1947 define(«vas_disk_gap», «15»)
1948 define(«vas_disk_height», «20»)
1949 define(«vas_disk_color», «grey»)
1950 define(«vas_x1», «vas_vmem_left_margin()»)
1951 define(«vas_x2», «eval(vas_x1() + vas_mem_width())»)
1952 define(«vas_x3», «eval(vas_x2() + vas_gap_width())»)
1953 define(«vas_x4», «eval(vas_x3() + vas_mem_width())»)
1954
1955 define(«vas_membox», «
1956         <rect
1957                 fill="$1" stroke="black" stroke-width="1"
1958                 x="eval(vas_vmem_left_margin() + $3)"
1959                 y="vas_vmem_top_margin()"
1960                 width="vas_mem_width()" height="$2"
1961         />
1962 »)
1963 define(«vas_vmem_unmapped_box», «
1964         <rect
1965                 fill="vas_vmem_unmapped_color()" stroke="black" stroke-width="1"
1966                 x="eval(vas_vmem_left_margin())"
1967                 y="eval(vas_vmem_top_margin() + $1)"
1968                 width="vas_mem_width()"
1969                 height="eval($2)"
1970         />
1971
1972 »)
1973 define(«vas_vmem_swapped_box», «
1974         <rect
1975                 fill="vas_vmem_swapped_color()" stroke="black" stroke-width="1"
1976                 x="eval(vas_vmem_left_margin())"
1977                 y="eval(vas_vmem_top_margin() + $1)"
1978                 width="vas_mem_width()"
1979                 height="eval($2)"
1980         />
1981
1982 »)
1983 define(«vas_pmem_unavail_box», «
1984         <rect
1985                 fill="vas_pmem_unavail_color()" stroke="black" stroke-width="1"
1986                 x="eval(vas_vmem_left_margin() + vas_mem_width() + vas_gap_width())"
1987                 y="eval(vas_vmem_top_margin() + $1)"
1988                 width="vas_mem_width()"
1989                 height="$2"
1990         />
1991
1992 »)
1993 define(«vas_vmem_hline», «
1994         <line
1995                 x1="vas_vmem_left_margin()"
1996                 y1="eval(vas_vmem_top_margin() + $1)"
1997                 x2="eval(vas_vmem_left_margin() + vas_mem_width())"
1998                 y2="eval(vas_vmem_top_margin() + $1)"
1999                 stroke-width="1"
2000                 stroke="black"
2001         />
2002
2003 »)
2004
2005 define(«vas_pmem_hline», «
2006         «<!-- pmem hline -->»
2007         <line
2008                 x1="eval(vas_vmem_left_margin() + vas_mem_width() + vas_gap_width())"
2009                 y1="eval(vas_vmem_top_margin() + $1)"
2010                 x2="eval(vas_vmem_left_margin() + 2 * vas_mem_width() + vas_gap_width())"
2011                 y2="eval(vas_vmem_top_margin() + $1)"
2012                 stroke-width="1"
2013                 stroke="black"
2014         />
2015
2016 »)
2017 define(«vas_arrow», «
2018         <line
2019                 x1="eval(vas_vmem_left_margin() + vas_mem_width())"
2020                 y1="eval(vas_vmem_top_margin() + $1)"
2021                 x2="eval(vas_vmem_left_margin() + vas_mem_width() + vas_gap_width() - 2)"
2022                 y2="eval(vas_vmem_top_margin() + $2)"
2023                 stroke-width="1"
2024                 stroke="black"
2025                 marker-end="url(#arrow)"
2026         />
2027 »)
2028 define(«vas_disk», «
2029         <rect
2030                 fill="vas_disk_color()" stroke="black" stroke-width="1"
2031                 x="vas_x3()"
2032                 y="eval(vas_vmem_top_margin() + vas_pmem_height()
2033                         + vas_disk_gap())"
2034                 width="eval(vas_x4() - vas_x3())"
2035                 height="eval(vas_disk_height())"
2036         />
2037         <ellipse
2038                 cx="eval(vas_x3() + vas_mem_width() / 2)"
2039                 cy="eval(vas_vmem_top_margin() + vas_pmem_height() + vas_disk_gap())"
2040                 rx="eval(vas_mem_width() / 2)"
2041                 ry="eval(vas_mem_width() / 4)"
2042                 fill="vas_disk_color()" stroke="black"
2043         />
2044         <ellipse
2045                 cx="eval(vas_x3() + vas_mem_width() / 2)"
2046                 cy="eval(vas_vmem_top_margin() + vas_pmem_height()
2047                         + vas_disk_gap() + vas_disk_height())"
2048                 rx="eval(vas_mem_width() / 2)"
2049                 ry="eval(vas_mem_width() / 4)"
2050                 fill="vas_disk_color()" stroke="black"
2051         />
2052 »)
2053
2054 <svg
2055         width="vas_width()" height="vas_height()"
2056         viewBox="0 0 100 eval(100 * vas_height() / vas_width())"
2057         xmlns="http://www.w3.org/2000/svg"
2058         xmlns:xlink="http://www.w3.org/1999/xlink"
2059 >
2060         <marker
2061                 id="arrow"
2062                 viewBox="0 0 10 10" refX="5" refY="5"
2063                 markerWidth="4" markerHeight="4"
2064                 orient="auto-start-reverse">
2065                 <path d="M 0 0 L 10 5 L 0 10 z" />
2066         </marker>
2067         vas_membox(«vas_vmem_color()», «vas_vmem_height()», «0»)
2068         vas_membox(«vas_pmem_color()», «vas_pmem_height()»,
2069                 «eval(vas_gap_width() + vas_mem_width())»)
2070         vas_vmem_hline(«10»)
2071         vas_vmem_hline(«40»)
2072         vas_vmem_unmapped_box(«40», «20»)
2073         vas_vmem_swapped_box(«60», «60»)
2074
2075         vas_pmem_unavail_box(«0», «10»)
2076         vas_pmem_hline(«20»)
2077         vas_pmem_unavail_box(«20», «30»)
2078         vas_pmem_hline(«80»)
2079
2080         vas_arrow(«5», «15»)
2081         vas_arrow(«25», «65»)
2082         vas_arrow(«130», «90»)
2083         vas_disk()
2084         vas_arrow(«90», «eval(vas_pmem_height() + vas_disk_gap()
2085                 + vas_disk_height() / 2)»)
2086 </svg>
2087 </div>
2088
2089 <p> Virtual memory is an abstraction of the available memory resources.
2090 When a process reads from or writes to a memory location, it refers
2091 to <em>virtual addresses</em> (illustrated as the left box of the
2092 diagram). Virtual addresses are mapped by the MMU to <em>physical
2093 addresses</em> which refer to physical memory locations (right
2094 box). The <em>mapped</em> virtual address space of a process is a
2095 collection of ranges of virtual addresses which correspond to physical
2096 memory addresses (blue areas). By storing less frequently-accessed
2097 chunks of virtual memory (yellow) on the swap area (grey), applications
2098 can use more memory than is physically available. In this case the
2099 size of the valid virtual addresses (blue and yellow areas together)
2100 exceeds the amount of physical memory (orange and green areas). Any
2101 attempt to access an unmapped memory location (red and yellow areas)
2102 results in a <em>page fault</em>, a hardware trap which forces the CPU
2103 back into kernel mode. The kernel then checks whether the address is
2104 valid (yellow) or invalid (red). If it is invalid, the kernel sends
2105 <code>SIGSEGV</code>, which usually terminates the process with
2106 the <code>segmentation fault</code> error. Otherwise it allocates
2107 a chunk of unused physical memory, copies the chunk from the swap
2108 area to the newly allocated memory and adjusts the mapping (i.e.,
2109 a yellow part becomes blue). The virtual memory concept increases
2110 stability and security because no process can access physical memory
2111 which belongs to the kernel or to other processes (orange areas). </p>
2112
2113 <p> We've already seen that the <code> fork(2) </code> system call
2114 creates a new process as a duplicate of the calling process. Since
2115 the virtual address space of the calling process (a) might be large
2116 and (b) is likely to be replaced in the child by a subsequent call
2117 to an exec function, it would be both wasteful and pointless to
2118 copy the full address space of the parent process to the child. To
2119 implement <code> fork(2) </code> efficiently, operating systems
2120 employ an optimization strategy known as <em> Copy on Write </em>
2121 (CoW). The idea of CoW is that if multiple callers ask for resources
2122 which are initially indistinguishable, you can give them pointers to
2123 the same resource. This function can be maintained until a caller
2124 tries to modify its copy of the resource, at which point a true
2125 private copy is created to prevent the changes becoming visible to
2126 everyone else. The primary advantage is that if a caller never makes
2127 any modifications, no private copy needs ever be created. The <code>
2128 fork(2) </code> system call marks the pages of the virtual address
2129 space of both the parent and the child process as CoW by setting a
2130 special bit in the <em> page table entry </em> which describes the
2131 mapping between virtual and physical addresses of the MMU. As for
2132 invalid memory accesses, the attempt to write to a CoW page results
2133 in a page fault that puts the CPU back into kernel mode. The kernel
2134 then allocates a new memory page on behalf of the process, copies
2135 the contents of the page which caused the fault, changes the page
2136 table mappings for the process accordingly and returns to user space.
2137 This all happens transparently to the process. </p>
2138
2139 <div>
2140 define(«asl_width», «300»)
2141 define(«asl_height», «400»)
2142 define(«asl_top_margin», «10»)
2143 define(«asl_text_width», «35»)
2144 define(«asl_mem_width», «25»)
2145 define(«asl_mem_color_env», «#fc8»)
2146 define(«asl_mem_color_stack», «#8fc»)
2147 define(«asl_mem_color_empty», «#ccc»)
2148 define(«asl_mem_color_heap», «#c8f»)
2149 define(«asl_mem_color_bss», «#8cf»)
2150 define(«asl_mem_color_data», «#cf8»)
2151 define(«asl_mem_color_text», «#f8c»)
2152 define(«asl_font_size», «5»)
2153
2154 define(«asl_arrow», «
2155         <line
2156                 x1="0"
2157                 y1="$1"
2158                 x2="eval(asl_text_width() - 2)"
2159                 y2="$1"
2160                 stroke-width="1"
2161                 stroke="black"
2162                 marker-end="url(#arrow)"
2163         />
2164 »)
2165 define(«asl_arrow_text», «
2166         <text
2167                 x="0"
2168                 y="$1"
2169                 font-size="asl_font_size()"
2170         >
2171                 $2
2172         </text>
2173 »)
2174
2175 dnl $1: y0, $2; height, $3: color, $4: high arrow text
2176 dnl $5: low arrow text, $6: desc
2177
2178 define(«asl_box», «
2179         <rect
2180                 stroke="black"
2181                 stroke-width="1"
2182                 x="asl_text_width()"
2183                 y="eval($1 + asl_top_margin())"
2184                 height="$2"
2185                 fill="$3"
2186                 width="asl_mem_width()"
2187         />
2188         ifelse(«$4», «», «», «
2189                 asl_arrow(«eval($1 + asl_top_margin())»)
2190                 asl_arrow_text(«eval($1 + asl_top_margin() - 2)», «$4»)
2191         »)
2192         ifelse(«$5», «», «», «
2193                 asl_arrow(«eval($1 + $2 + asl_top_margin())»)
2194                 asl_arrow_text(«eval(asl_top_margin()
2195                         + $1 + $2 - 2)», «$5»)
2196         »)
2197         <text
2198                 x="eval(asl_text_width() + asl_mem_width() + 2)"
2199                 y="eval($1 + $2 / 2 + asl_top_margin())"
2200                 dy="0.3em"
2201                 font-size="asl_font_size()"
2202         >
2203                 $6
2204         </text>
2205 »)
2206
2207 <svg
2208         width="asl_width()" height="asl_height()"
2209         viewBox="0 0 100 eval(100 * asl_height() / asl_width())"
2210         xmlns="http://www.w3.org/2000/svg"
2211         xmlns:xlink="http://www.w3.org/1999/xlink"
2212 >
2213         asl_box(«0», «10», «asl_mem_color_env», «2^64 - 1», «»,
2214                  «Environment»)
2215         asl_box(«10», «15», «asl_mem_color_stack», «», «base pointer»,
2216                  «Stack»)
2217         asl_box(«25», «30», «asl_mem_color_empty», «», «break point»,
2218                  «Empty»)
2219         asl_box(«55», «35», «asl_mem_color_heap», «», «», «Heap»)
2220         asl_box(«90», «10», «asl_mem_color_bss», «», «», «BSS»)
2221         asl_box(«100», «10», «asl_mem_color_data», «», «», «Data»)
2222         asl_box(«110», «10», «asl_mem_color_text», «», «0», «Text»)
2223 </svg>
2224 </div>
2225
2226 <p> The diagram on the left illustrates the layout of the virtual
2227 address space of a process. At the top of the address space are the
2228 argument vector and the environment variables. The <em>stack</em>
2229 stores the local variables of the functions which are currently
2230 being called, plus house-keeping data like the return addresses
2231 of these functions. As more functions are called, the stack grows
2232 downwards towards the lower addresses. Its current lower end is
2233 called the <em> base pointer</em>. The other variable area of the
2234 address space is the <em>heap</em>, which contains the memory that
2235 has been allocated on behalf of the process, for example with <code>
2236 malloc(3)</code>. As the process allocates more memory, the heap grows
2237 upwards, towards the stack. The current end of the heap is called the
2238 <em> break point</em>. The lower part of the address space contains
2239 three segments of fixed size. The <em>text</em> segment contains the
2240 compiled machine instructions of the executable, the <em>data</em>
2241 segment contains the initialized variables which are already known
2242 at compile time. Finally, the <em>BSS</em> segment is allocated and
2243 zeroed at execution time. This segment contains variables which should
2244 initialized to zero at startup. Unlike the data segment it is not
2245 stored in the executable. BSS stands for "Block Started by Symbol",
2246 which is a historic name coined in the 1950s. It has no relation to
2247 the real meaning of the segment. </p>
2248
2249 The exercises of this section invite the reader to look at the virtual
2250 address space of running processes to learn what happens when a
2251 dynamically-linked executable is being executed and how the resulting
2252 memory maps affect the virtual address space of the newly created
2253 process.
2254
2255 EXERCISES()
2256
2257 <ul>
2258         <li> Examine your own processes with <code>htop</code>, <code>ps
2259         ux</code> and <code>pstree -panuch $LOGNAME</code>. </li>
2260
2261         <li> Run <code>ls -l /proc/$$</code> and examine the environment of
2262         your shell process. </li>
2263
2264         <li> Run <code>kill -l</code> and discuss the meaning of signals
2265         1-15. Use <code>signal(7)</code> as a reference. </li>
2266
2267         <li> Create a zombie process: run <code>sleep 100&</code>. From
2268         another terminal, send <code>SIGSTOP</code> to the parent process
2269         of the sleep process (the shell), then send <code>SIGKILL</code>
2270         to the sleep process. Run <code>cat /proc/$PID/status</code> where
2271         <code>$PID</code> is the process ID of the sleep process. </li>
2272
2273         <li> Run <code>echo $$</code> to obtain the PID of an interactive
2274         shell that is running in a terminal. Send the <code>SIGSTOP</code>
2275         and <code>SIGCONT</code> signals to this PID from another terminal
2276         and see what happens when you type in the terminal that contains the
2277         stopped shell process. </li>
2278
2279         <li> The <code>ping(8)</code> utility catches <code>SIGQUIT</code>.
2280         In one terminal execute <code>ping localhost</code>. While this
2281         command runs in an endless loop, send <code>SIGQUIT</code> to the
2282         ping process from another terminal and see what happens. </li>
2283
2284         <li> Read <code>kill(2)</code> to learn what <code>kill -9 -1</code>
2285         does. Run this command if you are brave. </li>
2286
2287         <li> Why doesn't the <a href="«#»cd_script">cd script</a> work as
2288         expected? </li>
2289
2290         <li> Explain the difference between the two commands <code>X=foo
2291         bar</code> and <code>X=foo; bar</code>. </li>
2292
2293         <li> Run <code>set</code> and examine the environment variables of
2294         an interactive shell session. </li>
2295
2296         <li> Check this <a
2297         href="https://public-inbox.org/git/Pine.LNX.4.64.0609141023130.4388@g5.osdl.org/">email</a>
2298         from Linus Torvalds about why stdio is not that simple at all. </li>
2299
2300         <li> Run the command <code>ls / /does-not-exist</code>, redirect
2301         stdout and stderr to different files. </li>
2302
2303         <li> Consider the following shell code which uses stdio to first write
2304         to stdout, then to stderr. <code>echo foo; echo bar 1>&2</code>. Which
2305         circumstances guarantee that the "foo" line appears before the "bar"
2306         line in the output? </li>
2307
2308         <li> In the pipeline <code> foo | bar</code>, what is the
2309         buffering type of the file descriptor which corresponds to
2310         the <code> stdin </code> stream of the <code> bar </code>
2311         process? </li>
2312
2313         <li> Assume <code>foo</code> is a log file which increases due to
2314         some process appending data to it. Explain why the command <code>
2315         tail -f foo | while read; do echo new data; done </code> does not
2316         work as expected. Fix the flaw by changing the buffering type with
2317         <code>stdbuf(1)</code>. </li>
2318
2319         <li> Run <code>sleep 100 > /dev/null &</code>, examine open
2320         files of the sleep process by looking at suitable files in
2321         <code>/proc</code>. Do the same with <code>sleep 100 | head
2322         &</code>. </li>
2323
2324         <li> Run <code>ldd /bin/sh</code> and explain what happens when a
2325         shell is executed. </li>
2326
2327         <li> On a Linux system, run <code>cat /proc/$$/maps</code> or
2328         <code>pmap -x $$</code> to see the address space layout of your
2329         shell. Check <code>Documentation/filesystems/proc.txt</code>
2330         in the linux kernel source tree for the format of
2331         <code>/proc/$$/maps</code>. </li>
2332
2333         <li> Run <code>cat /proc/$$/smaps</code> and examine the values of
2334         the heap section. </li>
2335
2336         <li> Assume some program allocates a lot of memory so that the size of
2337         the valid virtual addresses is 1T large. Assume further that a software
2338         bug causes the content of a pointer variable to be overwritten with
2339         random garbage. Determine the probability that this pointer variable
2340         contains a valid address (assuming a 64 bit system). </li>
2341 </ul>
2342
2343 HOMEWORK(«
2344
2345 Explain how <code>PR_SET_CHILD_SUBREAPER</code> works and possible
2346 use-cases for this (Linux) feature.
2347
2348 »)
2349
2350 HOMEWORK(«
2351
2352 Explain in one paragraph of text the purpose of the <em>file
2353 creation mask</em> (also known as <em>umask</em>) of a process.
2354
2355 »)
2356
2357 HOMEWORK(«
2358
2359 When we said that each process runs on behalf of a user and that the
2360 ID of this user is part of the process metadata, we were simplifying
2361 matters. There are actually three different UIDs and three different
2362 GIDs: the <em>real UID</em>, the <em>effective UID</em>, and the
2363 <em>saved set-user ID</em>, and analogous for the group IDs. Explain
2364 the purpose of the three UIDs.
2365
2366 »)
2367
2368
2369 HOMEWORK(«
2370
2371 On a multi-CPU system the performance of a program can be
2372 enhanced by allowing for multiple flows of control. This is the
2373 idea behind <em>threads</em>, which are also called <em>lightweight
2374 processes</em>. Give an overview of threads, summarize the POSIX thread
2375 API (see <code>pthreads(7)</code>) and explain how the Linux-specific
2376 <code>clone(2)</code> system call can used to implement threads.
2377
2378 »)
2379
2380 HOMEWORK(«
2381
2382 Explain what the command <code>find /etc > /dev/null</code> does,
2383 and why you get some error messages. Assume you'd like to extract
2384 only those error messages which contain the string "lvm". Explain
2385 why <code>find /etc > /dev/null | grep lvm</code> does not work as
2386 expected. Come up with a similiar command that works.
2387
2388 », «
2389
2390 The command traverses the <code>/etc</code> directory recursively and
2391 prints all files and directories it encounters during the traversal to
2392 stdout. Since stdout is redirected to the NULL device by the <code>>
2393 /dev/null</code> construct, only the stderr stream containing the error
2394 messages makes it to the terminal.  This includes all subdirectories
2395 of <code>/etc</code> which cannot be traversed due to insufficient
2396 permissions (no "r" bit set). The proposed <code>find | grep</code>
2397 command does not work since the <code>|</code> operator is evaluated
2398 <em>before</em> any redirections specified by the find command
2399 take place. More precisely, stdout of the find process is redirected
2400 <em>twice</em>: First to one end of the pipe due to the <code>|</code>,
2401 then to the NULL device due to the <code>> /dev/null</code>. The
2402 last redirection "wins", so the <code>grep</code> process does not
2403 see any input. The command <code>find /etc 2>&1 > /dev/null | grep
2404 lvm</code> works. The following four redirections take place: First
2405 stdout of the <code>find</code> process and stdin of <code>grep</code>
2406 process are redirected to the two ends of the pipe. Next, due to
2407 the <code>2>&1</code> the stderr stream of the <code>find</code>
2408 process is redirected to the current destination of stdout, i.e.,
2409 to the pipe. Finally the <code>> /dev/null</code> redirects stdout
2410 of the find process to the NULL device. Hence error messages go to
2411 the pipe and are processed by <code>grep</code> as desired.
2412
2413 »)
2414
2415 HOMEWORK(«
2416 Run <code>ulimit -n</code> to see the maximal number of file descriptors you
2417 are allowed to create. Explain what this limit means with respect
2418 to multiple processes, multiple logins, and the <code>fork(2</code>) system
2419 call. Write a program in your language of choice which creates file
2420 descriptors in a loop until it fails due to the file descriptor
2421 limit. Then print the number of file descriptors the program was able
2422 to create.
2423 », «
2424 On our systems the limit is set to 1024. This means a single process
2425 can only have this many files open at any given time. Independent
2426 processes (like those coming from different login sessions) have no
2427 common file descriptors, even though they may open the same files. In
2428 this sense the file descriptor limit is a per-process limit. However,
2429 when a process calls <code>«fork(</code>») to create a new process, the new
2430 process inherits all open file descriptors from the parent. This can
2431 lead to the situation where a newly created process is unable to open
2432 <em>any</em> files. This property was actually used to break computer
2433 security. The <code>«O_CLOEXEC»</code> flag was introduced not too long
2434 ago to deal with this problem. See <code>open(2</code>) for details.
2435
2436 C program that opens the maximal possible number of file descriptors:
2437
2438 <pre>
2439         int main(void)
2440         {
2441                 int i;
2442
2443                 for (i == 0; open("/dev/null", O_RDONLY) >= 0; i++)
2444                         ;
2445                 printf("opened %d file descriptors\n", i);
2446                 exit(0);
2447         }
2448 </pre>
2449 »)
2450
2451 HOMEWORK(«
2452
2453 Search the web for the document called
2454 <code>vm/overcommit-accounting</code>. Discuss the pros and cons of
2455 the three possible overcommit handling modes.
2456
2457 »)
2458
2459 HOMEWORK(«
2460
2461 Read this
2462 <a
2463 href="https://utcc.utoronto.ca/~cks/space/blog/unix/MemoryOvercommit">blog
2464 posting</a> on the virtual memory overcommit issue. Explain the
2465 catch-22 situation described there in no more than two sentences.
2466
2467 »)
2468
2469 HOMEWORK(«
2470
2471 Describe, in a single paragraph of text, what a virtual dynamic
2472 shared object (VDSO) is and which type of applications benefit most
2473 from it.
2474
2475 »)
2476
2477 HOMEWORK(«
2478
2479 Describe the concept of <em> huge pages </em> and the Linux-specific
2480 implementation of <em> transparent </em> huge pages. Discuss the pros
2481 and cons of huge tables and explain the workloads which would benefit
2482 from a setup with huge pages enabled.
2483
2484 »)
2485
2486 HOMEWORK(«
2487 <ul>
2488         <li> Explain the concept of <em>address space layout randomization</em>
2489         (ASLR). </li>
2490
2491         <li> Run <code>bash -c</code> '<code>cat /proc/$$/maps</code>'
2492         repeatedly to see address space layout randomization in action. Discuss
2493         the pros and cons of ASLR. </li>
2494 </ul>
2495 »)
2496
2497 SUPPLEMENTS()
2498
2499 SUBSECTION(«cd_script»)
2500
2501 <pre>
2502         #!/bin/sh
2503         echo "changing CWD to $1"
2504         cd "$1"
2505 </pre>
2506
2507 SUBSECTION(«hello_world»)
2508
2509 <pre>
2510         #!/bin/sh
2511         echo "hello world"
2512 </pre>
2513
2514 SUBSECTION(«symlink_madness»)
2515
2516 <pre>
2517         #!/bin/sh
2518         mkdir foo
2519         touch foo/a
2520         ln -s ../foo foo/testdir
2521         ls -l foo/a foo/testdir/a foo/testdir/testdir/a
2522 </pre>
2523
2524 SECTION(«Further Reading»)
2525 <ul>
2526         <li> <a
2527         href="http://www.catb.org/~esr/writings/taoup/html/ch02s01.html">Origins
2528         and History of Unix, 1969-1995</a> by Eric Steven Raymond. </li>
2529
2530         <li> <a
2531         href="https://www.newyorker.com/business/currency/the-gnu-manifesto-turns-thirty">
2532         The GNU Manifesto Turns Thirty</a>, by Maria Bustillos. </li>
2533
2534         <li> <a href="https://lwn.net/Articles/924577/">The SCO lawsuit,
2535         20 years later</a> </li>
2536
2537         <li> <a
2538         href="http://www.catb.org/~esr/writings/unix-koans/end-user.html">
2539         The Koan of Master Foo and the End User</a>. </li>
2540
2541         <li> <a href="https://lwn.net/Articles/411845/">Ghosts of Unix Past:
2542         a historical search for design patterns</a>, by Neil Brown. </li>
2543
2544         <li> W. Richard Stevens: Advanced Programming in the Unix
2545         Environment. Addison Wesley. </li>
2546
2547 </ul>