Computer
Systems

Fall 2020
course
site
-->

CMU C libraries

For the second part of this course, you will want to use their C code libraries as examples and templates ... this will be particularly true for the I/O and process stuff, where they have wrappers that are safer and more robust than the standard C calls.

There's a link to the text's C code in the left margin.

Particularly important are these two files :

which give wrappers around common unix utilities and C library routines.

We'll be using these for the material in chapter 8, on processes ... which they call "ECF" - Exceptional Control Flow.

For example, consider their ecf/fork.c, along with its needed "#include" lines :

/* fork.c - Figure 8.15 from "Computer Systems" */
#include <stdio.h>
#include "csapp.h"
int main() {
    pid_t pid;
    int x = 1;
    pid = Fork();        // one process before this line ... two after.
    if (pid == 0){
        printf("child : x=%d \n", ++x);
    } else {
        printf("parent: x=%d \n", --x);
    }
    exit(0);
}

To compile and run this on jupyter.bennington requires several steps.

Notice first that it calls "Fork()" with a capital F; this is their function which is a wrapper around the unix "fork()" command. Its declaration is in include/csapp.h and source is in src/csapp.c :

pid_t Fork(void){
    pid_t pid;
    if ((pid = fork()) < 0)
    unix_error("Fork error");
    return pid;
}

which as you see is essentially just the unix fork() with some error checking built in.

So in addition to fork.c, we also need these two files, csapp.c and csapp.h. We also need the -pthread compile option.

So the steps are :

jupyter$ wget http://csapp.cs.cmu.edu/3e/ics3/code/src/csapp.c
jupyter$ wget http://csapp.cs.cmu.edu/3e/ics3/code/include/csapp.h
jupyter$ gcc -pthread csapp.c fork.c -o fork
jupyter$ ./fork
parent: x=0
child : x=2

And there you are.

(Note : pthread is "posix thread", which csapp.c references and therefore requires. There's a non-obvious difference between -lpthread i.e. "include thread library" and -pthread i.e. "include library and some macro definitions" ; google for example "pthread vs lpthread" for the gory details.)

https://cs.bennington.college /courses /fall2020 /systems /code /processes /cmu_libraries
last modified Mon November 16 2020 8:52 pm