Unix System Programming
Unix System Programming
Compilation in UNIX
• Stages of Compilation:
o Preprocessing: Directives like #include, #define are handled here. Use gcc -E to
view preprocessed code.
o Linking: Combines object files and resolves references (external libraries, other
files) into a final executable.
Tooling:
• gcc: Common flags include:
o -c: Compile to object file without linking.
o -o <filename>: Specify the output filename.
o -Wall, -Werror: Enable warnings, treat warnings as errors.
• Makefiles: Use make to streamline builds with dependencies, avoiding redundant
compilation.
• Debug Symbols: -g enables debugging; critical for using debuggers like gdb
Directories in UNIX
• Hierarchical Structure: Root (/) as the top-level directory, with subdirectories like:
o /bin: Essential binaries.
o /usr: User-installed software, binaries, libraries.
o /etc: Configuration files.
o /home: User home directories.
o /var: Variable files like logs, spools.
• Directory Commands:
o ls: List directory contents.
o mkdir, rmdir: Create/remove directories.
o cd: Change directory; pwd: Print working directory.
Listing and Creating Directories
UNIX File System Structure
• Linux File System Kernel:
o Manages the hierarchical directory structure, inodes, and data blocks.
• Key Data Structures:
o Inode: Contains metadata like permissions, owner, timestamps.
o Superblock: Information about the file system, such as size, number of inodes.
o Dentry: Directory entries, linking file names to inode numbers.
• File System Types: ext2, ext3, ext4:
o Journaling (ext3, ext4): Reduces risk of data corruption during unexpected
shutdowns.
o Performance: ext4 optimized for speed and handling large files.
Inspecting inode Information
Low-Level I/O
• File Descriptors:
o Integer identifiers for open files.
o Standard Descriptors:
▪ 0: stdin (input).
▪ 1: stdout (output).
▪ 2: stderr (error).
• File Operations:
o Opening and Creating:
▪ open(): Open or create files with flags like O_RDONLY, O_CREAT, and
file mode for permissions.
o Reading and Writing:
▪ read(fd, buffer, count): Reads count bytes from file descriptor fd into
buffer.
▪ write(fd, buffer, count): Writes count bytes from buffer to fd.
o Closing and Deleting:
▪ close(fd): Releases the file descriptor.
▪ Deleting Files: unlink(path) removes the directory entry, and deletes the
file when no process holds a file descriptor.
Process Management in Low-Level I/O:
• fork(): Creates new processes. Returns twice—0 to the child and PID to the parent.
• Pipes and Redirection:
o pipe(): Sets up unidirectional data flow between processes.
o Redirection (> for stdout, < for stdin): Used to manipulate I/O
sources/destinations in shells.