Final Review Flashcards
Explain the behind the scene steps behind “gcc” command
- The C preprocessor processed macros (#define and #include) in
the source code (“.c” file) and produced a new source code file
(unnamed)
2. The **C compiler** processed the output of the C preprocessor into assembly language code (“.s” file).
- The assembler processed the assembly language file and produced a
binary object file (“.o” file). - The linker combined the object file with necessary libraries and produced
the executable file (“a.out”).

What does it mean that C is “weakly typed”?
This means the compiler assumes the programmer knows what she/he is doing and allows casting of anything to anything else.
Explain the two types of C conversions: Explicit vs. Implicit.

What is a variable?
Memory that can hold the value. *Note: the deault value is mostly undefined, so treat it as random idea before initilization
List the components that everyta variable in C has.

When and where is the size of variable determined when a global variable is created? A local variable? A dynamic data varaible?
- Global data variables at compile time (.data)
- local data vairable at run-time (stack)
- dynamic data variables by the programmer (heap)
What is a pointer?
a variable continaing the address of another variable
(when initiated without a value, points to a random location in memory)
If we have the 2D array
int weekends[52][2];
What is the equivalent of weekends[3][1] in pointer arithmetic?
*(weekends + (3*2) + 1)
NOTE: “*” surrounds everything
General formula:
arr[r][c] = *(arr + (r*num_cols) + c)
All data objects of type FILE *…
- can be connected to file system files for reading and writing
- represent a buffered systemf chars (bytes) to be written or read
What do processors do?
From startup to shut down, CPU simply readsnd executes (intereprets) a sequence of instructions, one at a time… this sequenece is called the CPU’s control flow (of flow of control)
Define exception
An execpetion is a transfer of control to the OS kernel in response to some event (i.e. change in processor state)

What are asynchronous events/ interrupts?

What are synchonous exepctions?
Exceptions caused by events that occur as a result of executing an instruction. This includes:
- Traps
- Faults
- Aborts
Explain a Trap Exception and provide examples.
- Intentional, returns control to “next” instruction
- EX. system calls, breakpoint traps, special instructions

Explain Fault Exception and give an example.
- Unintential but possibly recoverable, either re-exectues faulting/current instruction or aborts
- EX: page fualts (recoverable), rotection faults (unrecoverable), floating point exceptions

Explain abort exceptions and provide an example.
- Unintentional and unreciverable, aborts the current program
- EX: llegal instruction, party error, machine check
What are exception tables?

What is a process?
A process is in an instance of a running programnd provides each program with two key abstractions

Explain the three states a process could be in.

What is the kernel?
The kernel is a shared chunk memory-resident OS code that manages processes
What is context switching?
Context switching is when control flow passes from one process to another.
Some examples of causes could be
- OS scheduling processs
- Kernel executing a system for user
- interrupts

Explain fork()

What are the three reasons a process becomes terminated?
1) Recieving a signal whose default action is to terminate
2) Returning from the main routine
3) Calling the exit function
Explain exit()

Explain reaping child processes.

Explain wait()

What macros can we use to get information about the exit status of a child process?
WIFEXITED and WEXITSTATUS

explain waitpid()

explain execve()

What is a signal in terms of ECF (Exceptional Control Flow)?

ECF: Exlpain sending a signal.

ECF: Explain recieving a signal.

ECF: Explain pending and blocking signals.

Explain signal()

Explain a Client Server Transaction.

How is a connection uniquely identified
by the socket adresses of its endpoints aka a socket pair

What is a socket?

Explain accept().
Accept waits for a connection request from the client to arrive on the given listening descriptor, then fills in the given socket address, and returns a connected descriptor that can be used to communicate with the client

Describe the socket interface as a whole. What functions/ actions do the client and the server each need to do for a successful connection?

What are races and give an example.
Races occur when the outcome depends on the arbitrary scheduling decisions elsewhere in the system
EX. who gets the last seat in an ariplane
What is a deadlock and provide an example.
Deadlocks occur when there is imporpper resource allocation prevents forward progress
EX. traffic gridlock
What is livelock?
Also known as startvation and fairness, this is when external events and or system schedulingdecisions can preventsub-task progress
EX. people always jump in front of you in line
What are the three different approaches to writing concurrent servers.

Explain the flaw in in Iterative Servers, where requests are processed one at a time.

Explain Process-based servers.
- Spawns a separate process for each client
- No shared state between them
- Simple and straightforward, but has issues…
- Listening sever process must reapzombie children to avoid fatal memory leak
- The parent process must close its copy of confd because the kernel wont close a connection until the refcount to confd is 0

Explain Event-based Servers
- ALso known as multiplexing
- Server maintains set of active connections
- an Array of connfds
- Repeats:
- Determine which desriptors (connfd’s pr listenfd) have pending inputs using select() - the arrival of a pending input is considered an event
- If listenfs has input, then accept connection and add new connfd to array
- Service all connfds withpending inputs

Explain thread-based servers.
- Very similar to the approach of using processes but instead just with threads
- Uses Pthreads library
- Need to malloc for connfdp to avoid race condition
- In the thread function, must
- copy the given void *vargo, into a new local stack variable connfd, basically removing that data from the heap and placing it on the stack
- call Pthread_detach() in order to run independtently of other threads and get reaped automatically by the kernel when it terminates
- free storage allocated to hold connfd
- close connfd, which closes this fd for all the threads because we share one fd table
- because if we didn’t close it here, the main thread would not know when to close it
- Not doing this can lead to running out of fd for long running programs

How do we know which variables in threaded C Porograms are share?
A variable x is shared if and only if multiple threads reference some instance of x
What does volatile mean?
It means please dont keep the intermidate value in a register. So, every instance of updating must be pushed back to memory
What does it mean when a function is atomic?
This means they can not be interrupted and taken on or off the processor. They are allowed to continue their execution until they are complete
What is a semaphore?
A semaphor is a non-negative global integer synchonization variable that is manipulated by P and V operations
Explain why mutexes work.
Since Semaphores can never be a nagitive number, mutexes essentially block off the unsade region where the variable would be less than 0 and ensures a safe trajectory

Explain the Producer-Consumer Problem.
- Key components of a Producer thread, Consumer thread, and shared buffer between the threads
- Common synchronization pattern:
- Producer waits for empty slot, inserts item in buffer, and notifies consumer
- Consumer waust for item, removes it from buffer,a nd notifers producer
- EX:
- Multimedia processessing: Producer creates MPEG video frames, consumer renders them
How many mutexes and semaphores are need to solve the Producer-Consumer Problem? And what are each of there uses?
Requires 1 mutex and two counting semaphores:
- mutex: enforces mutally exclusive access to the buffer
- slots: counts the available slots in the buffer
- items: counts the available items in the buffer
Explain the Readers-Writers Problem
It is a generalization of the mutal exclusion problem…
- Problem statement:
- Reader threads only read the object
- Writer threads modift the object
- Writers must have exclusive access to the object
- Unlimited number of readers can access the object
- Real World EX: Online airline reservation system
- There are variants of this problem:
- First readers-writers problem (favor readers)
- No reader should be kept waiting unless a writer has already been granted permission to use the object
- A reader that arrives after a waiting writer gets priority over the writer
- Secind readers-writers problem (favors writers)
- Once a writer is ready to write, it performs its write as soon as possible
- A reader that arrives after a writer must wait, even if the writer is also waiting
- First readers-writers problem (favor readers)

What is starvation?
When threads are blocked indefinitely because the other type of
How do we know if a function is thread-safe?
A fucntions is thread-safe iff it will always produce correct results when called repeatedly from multiple concurrent threads
What are the 4 classes of thread-unsafe functions?
- Class 1: Functions taht do not protect shared variables
- Class 2: Functiosn that keep state across multiple invocations
- Class 3: Functions that return a pointer to a static varibable
- Class 4: Functions that call thread-unsafe functions
Explain Class 1 Thread-Unsafe Function’s Fixes and Examples.
- Fix by using P and V semaphore operations
- EX. the badcnt.c & goodcnt.c examples where the volatile global variable of cnt was initially unprotected
- Issue: synchronization operations will slow down code
Explain Class 2 Thread Unsafe Function’s Fixes and Examples.
- Fix: Pass state as part of argument, and, thereby eliminate global state
- EX: Random number generator that relies o static state
- Consequence: programmer using rand_r (the thread safe version of rand) must maintain seed
Explain Class 3 Thread Unsafe Function’s Fixes and Examples.
- Fix 1: Rewrite function arguments so caller passes address of variable to store result into
- Requrires changes in caller and callee
- Fix 2: Lock and copy
- Requires simple changes in caller (and non in callee)
- However, caller must free memory
- EX. ctime & gethostbyname
When is a function reentrant?
A function is reentrant iff it accesses no shared variables when called by multiple threads
Explain Bind()
Bind asks the Kernel to associate the server’s given socket address with the given socket descriptor
Explain Socket()
Socket is used by clients and servers to create a socket descriptor given a domain, typem and protocol
Explain Listen()
Listen converts the given socketfd from an active socket to a listening socket, telling the kernel that the descriptor will be used by the server instead of the client
Explain Connect()
Connect attempts to establish a connections iwth the given server’s socket address, If successful, the given clientfd is ready for reading and writing
What are all the default actions of a signal?
- The process terminates
- EX. SIGKILL
- The process terminates and dumps core
- EX. SIGSEGV
- The process stops until restated by SIGCONT signal
- EX. SIGSTOP
- The process ignores the signal
- EX. SIGCHILD
What is implicit blocking mechanism?
- Kernel locks any pending signals of type currently being handled
- Ex. A SIGINT handler can’t be interrupted by another SIGINT
What is explicit blocking and unblocking mechanism?
- Using sigpromask function and its suppproting functions…
- sigemotyset - creates empty set
- sigfillset - adds every signal number to set
- sigaddset - add signal number to set
- sigdelset - deletes signal unmber from set
What is sigsuspend()?
Equivalent to atomic (uniterruptable) version of:
sigpeomask(SIG_BLOCK, &mask, &prev);
pause();
sigpromask(SIG_SETMASK, &prev, NULL);

What are all the items shared between threads?
- Global variables
- Program Code
- File Descriptor Table
- Heap
- Heap Pointer
What items are unique to each thread?
- Program Counter
- Stack Ppointer
- Register Values
When file sharing, information about the files are kept in what 3 levels/tables?
- Despriptor Table
- File Table
- V-node Table
Describe what a Desciptor Table is (shared or unique to processes? What kind of entries?)
- each process has its own table
- entries are index of file descriptors
- each open descriptor entry points to an entry in the file table
Describe what a File Table is (shared or unique to processes? What kind of entries?)
- shared by all processes
- entries contain informayion about file (current position, # of references, pointer to an entry in v-node table)
- Kernel only removes entry if reference count = 0
Describe what a V-node Table is (shared or unique to processes? What kind of entries?)
- Shared by all processes
- each entry contains info from stat structure
- Info in stat struct includes File access, File size, File type, etc