Programs CSCI 4061 Introduction to Operating Systems C Program Structure Libraries and header files Compiling and building programs Executing and debugging Instructor: Abhishek Chandra Assume familiarity with C programming 2 C Refresher Set of variables, types and functions Variables: Global: Visible in all functions Local: Visible within a single function Static: Visible to all functions within a file Types: structs, unions, typedefs Functions: User-defined or library functions Function main int main(int argc, char *argv[]) main is the program starting point argc: number of command-line arguments argv: array of command-line arguments What are the value of argc and argv for: myprog hello world myprog hello world 3 4 1
Standard Program Elements Parse the command line Check for syntax and extract various options Report error/usage if ill-formed command line Do the desired execution Read files, run threads, write output, etc. Cleanup and exit Free all resources Exit gracefully (print error msg if abnormal exit) Program Structure Modules: Independent and interacting parts of a program implementing specific functionality Typically implemented in separate files E.g.: Web browser: Module for tracking user input Module for communicating with server Module for displaying Web pages 5 6 C Program Files Header Files (.h) Header files Source files Libraries Contain types, function prototypes, constants Contain elements that are shared across modules Contain the interface exposed to external programs E.g.: library header files Default include path: /usr/include Program 7 8 2
Source files (.c) Core of the program modules Implement the functions of the program May contain static variables that are required only in that source file Contain include statements for header files to include global declarations and prototypes #include <stdio.h> #include decls.h Libraries Utility functions/system calls Pre-installed on the system Prototypes of functions called from program must be declared Include appropriate header files String library: #include <string.h> Libraries may have to be linked at compile time using -l<lib> flag cc o hello hello.c -lm 9 10 Programming Commandments Thou shalt write readable code Thou shalt use lot of documentation Comments and indentation Thou shalt use good coding style Meaningful variable/function names E.g.: sort_list() instead of foo() Use named constants instead of numbers E.g.: MAXLEN instead of 1024 Functions should be about 1 page long Put unrelated functions in separate files Error Handling If a function can return an error, check for it Check for every possible error, even if rare Return values from your functions Error codes on error Do not exit abruptly from your functions Exit gracefully from main() System/library calls: use perror() Library calls return -1, set errno Always check library calls for errors if (close(fd)==-1) perror( Failed to close the file ); 11 12 3
Program Compilation Preprocessor: Processes include statements, macro and constant definitions Compiler: Converts source code into assembly code Assembler: Converts assembly code into machine language Linker: Combines multiple object files into executable program Program Compilation hello.c hello.o #include <stdio.h> #define MAXLEN 1024 01110010100 0111... void print_msg() { char *msg= Hello World ; printf( %s\n, msg); } Compiler hello.s Print_msg: store this load that push register... Assembler Linker Object files, Libraries hello 13 14 Program Compilation: make make builds programs by using dependency trees Makefile allows multiple program dependencies to be specified in a file If a source/header file changes, make recompiles dependent targets recursively Program Execution Runtime environment Program arguments Environment variables Dynamic libraries Other programs and the Operating System hello: hello.o util.o gcc o hello hello.o util.o lm hello.o: hello.c hello.h gcc c hello.c 15 16 4
Program Arguments and Environment Command-line arguments: argc, argv Environment variables: Associated with each program Typically determined by the invoking shell environment Dynamically Linked Libraries Static vs. dynamic linking Statically linked libraries are linked into the executable at compile time Is this a problem? Dynamically linked libraries are loaded at runtime when the corresponding function is called System must be able to find dynamic libraries at runtime $LD_LIBRARY_PATH Default: /lib, /usr/lib 17 18 Other Programs and Operating System Other programs impact your program in several ways: Communication Sharing of data Affect performance Operating system: Provides all the low-level services and utilities Manages resources for your program Provides security and isolation Testing and Debugging Run lots of test-cases Ill-formed command lines (too few, too many arguments) Missing files, data, input, etc. Boundary conditions: NULL pointers, zero-size arrays, (n+1)-length strings Too long/too short strings, numbers Read specifications VERY carefully! Ask for clarifications ASAP 19 20 5
Debugging Iterative process Using printf() Track variables, functions by printing out useful information Edit, recompile, run to get additional info Turn debugging on/off using compiler flags #ifdef DEBUG fprintf(stderr, val=%d\n, val); #endif Debugging: gdb GNU debugger Allows examining the program in slow-motion with pauses and fast-forwards (playbacks, but no rewinds) Set breakpoints Step through program Examine variable values Use g flag while compiling program gcc g o hello hello.c 21 22 Program Performance Correctness and Functionality Quantitative Metrics Runtime Latency Throughput System Resource usage CPU time, memory, disk space, network bandwidth Observing a Running Program time: Get the runtime of your program (both user and kernel time) ps: Gives information about running programs in the system (processes) top: Gives resource usage information (CPU share, memory, running time, status, etc.) strace: Trace system calls 23 24 6