Systems programming
14 steps in 6 sets of C.
C talking to the operating system. Environment and exit codes, time, processes and signals, files and directories, and finally sockets.
This is POSIX territory, which is to say it is what Unix looks like from the inside. Fourteen steps, and it explains a lot of behavior you have previously just worked around.
Program environment
- Command-line argumentsargv[0] is the program name, and argv[argc] is always NULL.
- Parsing options with getoptgetopt walks argv, handling clustered flags and their arguments.
- The environmentgetenv reads a variable, and returns NULL when it is not set.
- Feature test macrosStrict ISO mode hides POSIX declarations until you ask for them by name.
Time
- Time and formattingtime gives seconds, localtime breaks them apart, strftime formats them.
- Measuring elapsed timeclock counts processor time; use CLOCKS_PER_SEC to make it meaningful.
Processes & signals
- forkfork returns twice: zero in the child, the child's pid in the parent.
- Replacing the process with execexec never returns on success, because the process becomes the new program.
- Pipes between processesA pipe is a pair of descriptors: the child writes, the parent reads.
- SignalsA handler runs on interrupt, and it may only touch async-signal-safe things.
Files & directories
- Inspecting a filestat fills a struct with size, mode and timestamps.
- Walking a directoryopendir, readdir, closedir: three calls and a loop.
Sockets
- A TCP clientsocket, connect, write, read, close — the whole client in five calls.
Encore
- tcp_echo.cA single-threaded echo server: bind, listen, accept, echo, repeat.