CPS 356 Practice Problems



Outline


Introduction

  1. What is an operating system?
  2. What are the primary goals of an operating system?
  3. (true / false) UNIX is a preemptive multitasking (time-shared) OS.
  4. List three properties of the UNIX operating system, one of which must not also be a property of Microsoft Windows.
  5. Draw the conceptual architecture of the UNIX system. Hint: it contains seven layers of concentric circles.
  6. What are the two primary interprocess communication mechanisms used in UNIX and C programming presented in class?
  7. Consider the following C code:
    FILE* fptr = fopen ("input.txt", "r");
    Draw the data structure to which fptr points and describe each field of it.
  8. When is an entry in the system file table freed?
  9. When is an entry in the in-memory inode table freed?
  10. What does the following code do?
    while((n=read(fd, buf, bufsize)) > 0);
  11. (true / false) The buffer written to by printf is part of the user space.
  12. Write a complete C program which implements the UNIX cat command. For full credit, your program must read from standard input and file input (with one or more files) and check for all possible errors, as demonstrated in class.

  13. What problem may occur with the following code?
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    int main (int argc, char** argv) {
       char lastname[24];
    
       if (argc < 2) {
          fprintf (stderr, "USAGE: %s string\n", argv[0]);
          exit (1);
       }
    
       strcpy (lastname, argv[1]);
       exit (0);
    }
        
    Describe how you would need to modify this program to fix the problem and then show the corrected code.

  14. Give the value of argc in a.out in the following command line:

    $ ./a.out < infile > outfile.

  15. Write a complete C program which writes its command-line arguments (including the command name) to stdout, one per line. Do not use the [ or ] characters anywhere in your program.
  16. Write a complete C program which accepts three files as command-line arguments. The first file given at the command line contains only an integer (the base) while the second contains only an integer (the exponent). The program computes the value of the base raised to the exponent, and prints the resulting product to the file given by the third command-line argument. Your program must contain code to check for all possible errors (including the absence of one or more of the command-line arguments) and print all error messages to stderr.


Processes and threads

  1. What is a process?
  2. Draw a diagram illustrating the logical layout of a process image in main memory. Be precise and complete. Clearly label all sections and aspects. Indicate in which direction each section of the memory grows.
  3. Draw the state transition diagram for the lifecycle of a process. Clearly, label both state nodes and directed edges. Hint: it contains five states, but more than five directed edges.
  4. What is multiprogramming?
  5. What is timesharing?
  6. What is a context switch?
  7. What is a system call and how does it differ from a library call?
  8. What does a system call cause to happen?
  9. What is an interrupt?
  10. (circle one) An interrupt can be generated by hardware only, software only, or hardware or software.
  11. Give an example of an event which causes an interrupt to be generated.
  12. What is a signal? What generates signals?
  13. Signals occur asynchronously. Explain what this means.
  14. Hardware devices generate interrupts asynchronously. What does this mean?
  15. Give a signal which cannot be ignored or caught by a handler?
  16. How do interrupts/signals add concurrency to a program?
  17. What is a device driver?
  18. Adding more main memory to a computer system makes programs run faster. Explain why clearly.
  19. (fill in the blank)

    Adding more main memory to a computer system increases the degree of _________________________.

  20. Assume POSIX guarantees that the function mystery is async-signal safe. This means the mystery can be safely called from within a signal handler. What else does this imply about mystery?
  21. (true / false) Since POSIX guarantees read to be async-signal safe, we need not restart read if it is interrupted by a signal.
  22. Explain the role played by signals in non-blocking I/O (also called asynchronous I/O).
  23. (true / false) Non-blocking I/O is not possible without the use of interrupts/signals.
  24. How does fork affect the system file table?
  25. (true / false) The buffer written by printf is not duplicated by fork.
  26. Consider the following C program.
    #include <stdio.h>
    #include <unistd.h>
    
    main() {
       fork(); /* fork number 1 */
       fork(); /* fork number 2 */
       fork(); /* fork number 3 */
       printf ("pid: %ld, ppid: %ld\n", (long) getpid(), (long) getppid());
    }
        

    Trace this program to determine how many processes are created. Assume that no errors occur. Draw a graph which shows how the processes created are related.

    In this graph each process will be represented by a small circle containing a number which represents the fork which created the process. The original process will contain 0 and the process created by the first fork will contain 1. There will be arrows from each parent to all of its children. Each arrow should point in a downward direction. Be careful.

  27. Consider the following C program:
    #include <stdio.h>
    #include <stdlib.h>
    #include <unistd.h>
    
    int main() {
       pid_t childpid = 0;
       int i;
    
       for (i = 1; i < 4; i++)
          if ((childpid = fork()) == -1)
             break;
    
       return 0;
    }
        

    Trace this program to determine how many processes are created. Assume that no errors occur. Draw a directed graph which shows how the processes created are related.

    In this graph each process will be represented by a small circle containing a pid. You may assume the pid of the original process is 0 and that pid's are assigned in increasing order of process creation, (i.e., 1, 2, 3, ...). There will be arrows from each parent to all of its children. Each arrow should point in a downward direction.

    Now modify this program in place above so that each parent process waits for all of its children to terminate before it terminates. You must only add code to the above program; you must not remove any code.

  28. What output is generated by the following program?
    #include <stdio.h>
    #include <unistd.h>>
    
    main() {
       printf ("Zippy Yay Cool");
       fork();
    }
        
  29. The Fibonacci sequence is the series of numbers 0, 1, 1, 2, 3, 5, 8, ... Formally, it is expressed as

    fib_0 = 0
    fib_1 = 1
    fib_n = fib_{n-1} + fib_{n-2}.
        

    Write a complete C program which spawns n process which cooperate to compute and print the first n Fibonacci numbers, where n is given as a command-line argument, such that each process computes and prints only one number in the sequence. The processes must terminate in reverse order of creation. Be careful to synchronize the processes so that the numbers are printed in the correct order. For instance,

    $ ./a.out 2
    0 1
    $ ./a.out 3
    0 1 1
    $ ./a.out 4
    0 1 1 2
    $ ./a.out 5
    0 1 1 2 3
    $ ./a.out 6
    0 1 1 2 3 5
    $ ./a.out 7
    0 1 1 2 3 5 8
    $ ./a.out 12
    0 1 1 2 3 5 8 13 21 34 55 89
    $
        

  30. Consider the following C program.
    #include <stdio.h>
    #include <unistd.h>>
    
    int main() {
       pid_t childpid;
       int i;
    
       childpid = fork();
    
       for (i = 0; i < 10 && childpid == 0; i++)   {
    
          if (childpid == -1) {
             perror("Failed to fork.");
             return 1;
          }
    
          fprintf (stderr, "A");
    
          childpid = fork();
    
          if (childpid == 0)   {
             fprintf (stderr, "B");
             childpid = fork();
          }
       }
    
       return 0;
    }
        

    How many processes does this program spawn (include the original process in your count)? Give a brief explanation of how you arrived at your answer.

    What is the output of this program?


  31. Write a complete C program which creates a chain of n (given as a command-line argument) processes which terminate in reverse order of creation. Check for errors.
  32. (true / false) A program containing system calls will always execute faster than the same program where the systems calls are replaced with analogous library calls.
  33. (true / false) A library function, such as printf, is part of the C language.
  34. (true / false) A dynamically linked executable will always be larger than its statically linked analog.
  35. Suppose you have a file \$HOME/tmp/logutil. Give a complete command line to set the permissions of logutil so that it would be readable by you, writable by you and your group, and executable by others, without giving any extraneous permissions.
  36. List three types of file information stored in a file's inode.
  37. Give one example of file information which is not in a file's inode.
  38. (circle one) A symbolic link points to a (inode number or filename).
  39. (true / false) The file representing a symbolic link does not have its own inode number.
  40. What is an orphan process?
  41. (true / false) All zombie processes become orphans.
  42. What does the following program guarantee?
    #include <stdio.h>
    #include <sys/wait.h>
    
    int main() {
       int pid;
       int status;
       printf ("Hello World!\n");
       pid = fork();
    
       if (pid == -1) {
          perror ("bad fork");
          exit (1);
       }
    
       if (pid == 0)
          ...
       else {
          wait (&status);
          ...
       }
    }
        
  43. Consider the following:

    A process fully terminates when

    • its parent has executed wait(&status), and
    • it exits or is killed by a signal (e.g., <ctrl-c>).

    Answer the following questions.

    1. In what order do the steps above occur during normal process termination?
    2. What happens if they occur in the reverse of normal order?
    3. What happens if (b) occurs, but (a) never occurs?

  44. Consider the following series of command lines and outputs (executed in this order):

     1 export PAGER=less
     2 EXINIT="showmode showmatch ruler"
     3 ksh
     4 echo $PAGER
     5
     6 echo $EXINIT
     7
     8 export A=10
     9 exit
    10 echo $A
    11
    
    1. What is printed on line 5?
    2. What is printed on line 7?
    3. What is printed on line 11?

  45. Write a complete C program which implements ls -l >> ls.out as efficient as possible.

    Do not re-implement ls. Rather re-use the system's ls command. Do not use the system call system in your program.

  46. What would you do to setup your environment such that files are created readable by only you, your group, and others, but writable by only you and your group, without giving any extraneous permissions, in such a way that this change would be in effect each time you logged in?
  47. (true / false) Writing to a pipe is not an atomic operation.
  48. (true / false) Reading from a pipe is not an atomic operation.
  49. (circle one) Processes in a UNIX pipeline (e.g., ls | more) execute (sequentially or concurrently).
  50. What are the two primary mechanisms by which processes communicate?
  51. Suppose a command mystery writes its output to stderr. Give a command-line which would pipe this output to wc -l.
  52. Consider the following:
    $ ls -l
    total 89
    -rw-------  1 lucy  users    196 Jun 25 09:41 Makefile
    -rw-------  1 lucy  users  90001 Jun 25 09:42 popd.eee
    -rw-------  1 lucy  users      8 Jun 25 09:43 pushd.aaa
    -rw-------  1 lucy  users  11056 Jun 25 09:43 pushd.ddd
    -rw-------  1 lucy  users   3664 Jun 25 09:43 pushd.lll
    -rw-------  1 lucy  users  64411 Jun 25 09:44 pushd.ppp
    -rw-------  1 lucy  users   8319 Jun 25 09:42 pushd.fff
    $
    $
    $ cat Makefile
    SRC = pushd
    
    all: $(SRC)
    
    $(SRC): $(SRC).ppp
    
    $(SRC).ppp: $(SRC).ddd
            src2dev -o $(SRC).ppp $(SRC)
    
    $(SRC).ddd: $(SRC).fff popd.eee
            hexroff $(SRC)
    
    clean:
            touch *.fff
            -rm $(SRC).lll $(SRC).aaa $(SRC).ddd $(SRC).ppp
    $
        

    Which commands, if any, do the following command lines force to execute?
    The following command lines are completely independent of each other (i.e., the second is not run after the first, and the first is not run after the second).

    • $ make pushd
    • $ make

  53. Consider the following:
    $ ls -l
    total 89
    -rw-------  1 lucy  users    196 Jun 25 09:41 Makefile
    -rw-------  1 lucy  users  90001 Jun 25 09:42 fig1.eps
    -rw-------  1 lucy  users      8 Jun 25 09:43 final.aux
    -rw-------  1 lucy  users  11056 Jun 25 09:43 final.dvi
    -rw-------  1 lucy  users   3664 Jun 25 09:43 final.log
    -rw-------  1 lucy  users  64411 Jun 25 09:44 final.ps
    -rw-------  1 lucy  users   8319 Jun 25 09:42 final.tex
    $ cat Makefile
    SRC = final
    
    all: $(SRC)
    
    $(SRC): $(SRC).ps
    
    $(SRC).ps: $(SRC).dvi
            dvips -o $(SRC).ps $(SRC)
    
    $(SRC).dvi: $(SRC).tex fig1.eps
            latex $(SRC)
    
    clean:
            touch *.tex
            -rm $(SRC).log $(SRC).aux $(SRC).dvi $(SRC).ps
    $
        

    Which commands, if any, do the following command lines force to execute?
    The following command lines are completely independent of each other (i.e., the second is not run after the first, and the first is not run after the second).

    • $ make final
    • $ make

  54. What is a thread, and how does it differ from a process?

    What does a thread share with its process, and what does it not share with its process?

  55. (fill in the blank with the appropriate adjective)

    A thread is sometimes called a ___________________ process.

  56. Suppose we develop two concurrent solutions to the same problem: one using one process with multiple threads of control and one using multiple processes, each with a single thread of control. If turnaround time is the only evaluation criterion, in general, which solution is preferred? Explain why clearly.
  57. Consider the following C program (ref. [USP] program 2.5, p. 41 and exercise 2.20, p. 42):
    /* a function which sorts an array of integers and
       counts the number of interchanges made in the process */
    static int count = 0;
    
    /* return true if interchanges are made */
    static int onepass (int a[], int n) {
       int i;
       int interchanges = 0;
       int temp;
    
       for (i = 0; i < n-1; i++)
          if (a[i] > a[i+1]) {
             temp = a[i];
             a[i] = a[i+1];
             a[i+1] = temp;
             interchanges = 1;
             count++;
          }
       return interchanges;
    }
    
    void clearcount() {
       count = 0;
    }
    
    int getcount() {
       return count;
    }
    
    /* sort a in ascending order */
    void bubblesort (int a[], int n) {
       int i;
       for (i = 0; i < n-1; i++)
          if (!onepass (a, n-i))
            break;
    }
        

    Give the storage class and linkage class for each of the following entities in this program:

    • the count variable
    • the onepasss function
    • the getcount function
    • the i variable in the bubblesort function

  58. Recall that r_strtok() is the thread-safe version of strtok. What does thread-safe mean?
  59. Write a complete Java program which spawns two concurrent Threads which communicate through a shared buffer (use a simple char variable wrapped in an object). One thread writes the character 'f' (for full) to the buffer and the other thread prints the buffer to standard output only after the thread has written to it (i.e., this program must not have a race condition).

    For full credit, the two threads must be running concurrently, and the buffer object must be shared between the two threads, not duplicated. You may not use any Java synchronization mechanisms to solve this problem (e.g., semaphores or monitors) because none are needed to solve it. No credit will be awarded to solutions using Java synchronization mechanisms.

  60. Explain what the following command-line does:
    $ date >/dev/tty
  61. (true / false) A controlling terminal can be redirected from the command line like standard input and standard output.


Scheduling

  1. Scheduling algorithm X is preemptive. What does this mean?
  2. What is job scheduling?
  3. What is process scheduling?
  4. For the process set below, draw a complete Gantt chart showing when each process has access to the CPU, and compute average turnaround time, for each of the following scheduling algorithms. If more than one event happen at the same time, always conduct process scheduling before job scheduling.

    process arrives burst time
    p1 0 22
    p2 4 8
    p3 10 20
    p4 14 10
    p5 28 4

    • First-come, first-served
    • Shortest job first (non-preemptive)
    • Shortest remaining time first (preemptive)
    • Round-robin with a quantum of 10

  5. For the process set below, draw a complete Gantt chart showing when each process has access to the CPU, and compute average turnaround time, for each of the following scheduling algorithms. The processes are assumed to have arrived in the order p1, p2, p3, p4, p5, all at time 0.

    process burst time priority
    p1 10 3
    p2 1 1
    p3 2 4
    p4 1 5
    p5 5 2

    • First-come, first-served
    • Shortest job first (non-preemptive)
    • Non-preemptive priority (a smaller priority number implies a higher priority)
    • Round-robin with a quantum of 1


Synchronization

  1. Name the only three distinct, primitive solutions to the critical section problem presented in class, where primitive means `does not rely on some other primitive solution.'
  2. What is a semaphore?
  3. What is a spinlock?
  4. (true / false) Starvation is not possible with a fair semaphore.
  5. The Sleeping-Barber Problem:

    A barbershop consists of a waiting room and n chairs and a barber room with one barber chair. If there are no customers to be serviced, the barber goes to sleep. If a customer enters the barbershop and all chairs are occupied, then the customer leaves the shop. If the barber is busy but chairs are available, then the customer sits in one of the free chairs. If the barber is asleep, the customer wakes up the barber.

    Write a complete Java program using a monitor to coordinate the barber and the customers. Specifically, using only the Customer and Factory classes below, complete the definition of the BarberShopMonitor class by providing a definition for the customerEnters(int id) method. Do not modify these classes at all. You must only complete the data member section and provide definitions for the constructor and the customerEnters(int id) method. Moreover, for full credit, your solution must be fair, (i.e., no new customer should be able to cut ahead of a customer in the waiting room). If you recall, the semaphore solution presented in class suffered from this problem.

    public class Factory {
       public static final int NUM_OF_CHAIRS = 10;
       public static final int NUM_OF_CUSTOMERS = 100;
    
       public static void main(String args[]) {
          BarberShopMonitor bsmonitor = new BarberShopMonitor(NUM_OF_CHAIRS);
    
          for (int i = 0; i < NUM_OF_CUSTOMERS; i++) {
             (new Thread(new Customer(i, bsmonitor))).start();
             if ((i % 3) == 0) SleepUtilities.nap();
          }
       }
    }
    
    class Customer implements Runnable {
    
       int id;
       BarberShopMonitor bsmonitor;
    
       Customer (int id, BarberShopMonitor bsmonitor) {
          this.id = id;
          this.bsmonitor = bsmonitor;
       }
    
       public void run() {
          bsmonitor.customerEnters(id);
       }
    }
    
    class BarberShopMonitor {
    
       BarberShopMonitor(int num_chairs) {
    
       }
    
       void customerEnters(int id) {
    
       }
    
       private void service(int id) {
          System.out.println ("Customer " + id + " is being serviced.");
          SleepUtilities.nap();
          System.out.println ("Customer " + id + " is done being serviced.");
       }
        
  6. Solve the following three problems in the Sleeping Barber problem.

    problem 1: Assume the barber is in use and there is only one chair left in the waiting room. Further, assume that a new customer slices after trying to acquire the barber, but before trying to acquire a chair in the waiting room. Under these circumstances, a new customer can occupy the last available chair in the waiting room, effectively cutting the line.

    • possible solution: make barber tryacquire() and waiting room tryacquire() atomic.

    problem 2: Assume the barber is available, but the waiting room is full. In this scenario, a new customer can cut the entire line.

    • possible solution: do waiting room tryacquire() before barber tryacquire()

    problem 3: Assume the barber is available and the waiting room is full. Further, assume that a customer in the waiting room slices after acquiring the barber, but before release their chair in the waiting room. Under these circumstances, a new customer will leave the shop because their are no seats available in the waiting room, even though there really is one available.

    • possible solution: make barber tryacquire() and release() of chair in waiting room atomic.

    Can all three of these problems be solved concomitantly in a semaphore solution to the Sleeping Barber problem, or is a monitor necessary? In more general terms, are semaphores and monitors as powerful as each other, or are there some problems for which a semaphore solution does not exist, though a monitor solution does exist?

  7. What is a monitor?
  8. When a monitor uses signal and exit semantics, as opposed to signal and continue semantics, where do the signaling threads/processes go?
  9. Explain why you must only use the Java wait() method within the body of a while loop, and never within the body of an if statement.
  10. Suppose, a file is to be shared among several different processes. The file can be accessed concurrently by several processes as long as the sum of all pids associated with all of the processes currently accessing the file is less than n. Define a monitor using the Hoare monitor model which coordinates access to the file given this constraint. You may assume that no pid is greater than n.

  11. Consider only three thread types (A, B, and C) with the following constraints:

    • mutual exclusion among the Cs,
    • maximum 5 Bs in at one time,
    • mutual exclusion between the As and Bs,
    • mutual exclusion between the As and Cs, and
    • when a type X thread leaves the monitor, if a non-X thread type and a type X thread both want and are safe to enter the monitor, the non-X thread type has priority.

    Complete the definition of the Java monitor Monitor class below to solve this problem. Do not add any new methods to the Monitor class, or any new classes. Only complete the data member section and provide definitions for the constructor and the 6 entry and exit methods.

    import java.util.concurrent.*;
    import java.util.concurrent.locks.*;
    
    class Monitor {
       ReentrantLock lock;
    
       Monitor() {
          lock = new ReentrantLock();
    
       }
    
       public void Aentry() {
          lock.lock();
    
          lock.unlock();
       }
    
       public void Aexit() {
          lock.lock();
    
          lock.unlock();
       }
    
       public void Bentry() {
          lock.lock();
    
          lock.unlock();
       }
    
       public void Bexit() {
          lock.lock();
    
          lock.unlock();
       }
    
       public void Centry() {
          lock.lock();
    
          lock.unlock();
       }
    
       public void Cexit() {
          lock.lock();
    
          lock.unlock();
       }
    }
        
  12. Consider only three thread types (A, B, and C) with the following constraints:

    • mutual exclusion among the As,
    • mutual exclusion between the Bs and Cs,
    • mutual exclusion between the As and Cs, and
    • priority to the As (i.e., additional Cs must not enter the if one or more As are waiting to enter the , and if an opportunity arises to signal an A or C, signal the A.)

    Implement a Java monitor without condition variables to coordinate the activity of these threads (i.e., use the implicit monitor available in any Java object, rather than building a monitor from first principles. This also means you are unable to use Java condition variables).

  13. A group of fraternity brothers and sorority sisters is having a party and drinking from a large communal keg which can hold servings of root beer. One unlucky pledge is not allowed to participate in the party and rather must sleep in the tool shed. This particular pledge also has the unfortunate responsible of replacing the keg each time it empties. When a guest wants to drink, he or she fills a cup from the keg, unless the keg is empty. If the keg is empty, the guest goes to the tool shed, obnoxiously wakes up the pledge, returns to the party, and then waits to drink until the pledge has returned with a new keg. The guest who wakes up the pledge need not be the guest to drink the first cup from the new filled keg. In other words, your solution need not prevent starvation. The behavior of the guests and the unlucky pledge is specified by the following Java classes:

    class Guest implements Runnable {
        House house;
        Guest (House house) {
           this.house = house;
        }
        public void run {
           house.tellPledgeIfKegEmpty();
           house.getServingFromKeg();
           // drink
        }
    }
    
    class Pledge implements Runnable {
        House house;
        Pledge (House house) {
           this.house = house;
        }
        public void run {
           while (house.getNumGuests() > 0) {
              house.waitForKegToEmpty();
              house.getNewKegOfNservings();
           }
        }
    }
    
    class Party {
       private static final int CAPACITY_OF_KEG = 24;
       private static final int NUM_GUESTS = 100;
    
       public static void main(String args[]) {
    
          House house = new House(CAPACITY_OF_KEG, NUM_GUESTS);
    
          (new Thread (new Pledge(house))).start();
    
          for (int i=0; i < NUM_GUESTS; i++)
             (new Thread (new Guest(i, house))).start();
       }
    }
        

    Develop a complete Java semaphore solution to this problem. Specifically, complete the definition of the House class below. Do not add any new methods to the House class, or any new classes. Only complete the data member section and the definition of the constructor, and provide definitions for the four methods. Your solution must avoid deadlock and only awaken the pledge when the keg is empty. You must not use a monitor to solve this problem.

    Hint: in addition to the standard acquire and release semaphore operations, you may also assume availablePermits (which returns the semaphore value) and release(int n) (which adds n to the semaphore value) operations.

    class House {
       int capacity_of_keg;
       int num_guests;
    
       House (int capacity_of_keg, int num_guests) {
          // keg starts full
          this.capacity_of_keg = capacity_of_keg;
          this.num_guests = num_guests;
          
       }
    
       void tellPledgeIfKegEmpty() {
    
       }
    
       void getServingFromKeg() {
    
       }
    
       void waitForKegToEmpty() {
    
       }
    
       void getNewKegOfNservings() {
    
       }
    
       public int getNumGuests() {
          return num_guests;
       }
    }
        
  14. Solve the Party problem above using the classical Hoare monitor model. The pledge process and the guest processes are described as follows:

    process Guest {
       while (true) {
          guest_entrance();
          // 
          guest_exit();
       }
    }
    
    process Pledge {
       while (true) {
          pledge_entrance();
          // 
          pledge_exit();
       }
    }
        

    Provide a complete definition of the monitor (i.e., provide the declarations/definitions of the shared data as well as the definition of the entrance and exit procedures).

  15. Solve the Party problem above using the Java monitor model. The behavior of the guests and the unlucky pledge is specified by the Java classes below. Provide the definition of the Java monitor House class below to solve this problem. Only provide the definitions of the guestentrance, guestexit, pledgeentrance, and pledgeexit methods. Assume the exact same Party class as given in problem 2. Since the Java monitor model does not follow Hoare's model completely (or at all), you need not translate your solution to the problem 2 directly into Java (i.e., it is okay to take a different solution approach).

  16. In software engineering, a design pattern is a general reusable solution to a re-occurring problem in software design. There are catalogs of design patterns. One such pattern is called the Singleton pattern. It ensure that only one instance of an object is created. For instance, if we have a class called BestFriend, we wish to allow only one instance of it. Thus, rather than creating a BestFriend object using its constructor, we instead declare the constructor as private and provide a public static method getInstance() for object creation. Recall a static method is one which need not be called through a particular instance of an object. Rather it is called through the class itself akin to a function in C (which also is not associated with an object). For instance,

    BestFriend mary = BestFriend.getInstance();

    The following is one strategy for implementing the Singleton pattern. The idea behind this approach is to use lazy initialization, whereby we create an instance of the object only when it is needed (i.e., when getInstance()) is first called.

    public class BestFriend {
       private static BestFriend instance = null;
    
       private BestFriend() { }
    
       public static BestFriend getInstance() {
          if (instance == null)
             instance = new BestFriend();
          return instance;
       }
    }
        

    Does this implementation of the Singleton pattern involve a race condition? If so, identify it (be clear and specific) and modify the implementation above in place to eliminate the race condition. If not, state why not.

  17. Suppose a file is to be shared among several different processes. The file can be accessed concurrently by several processes as long as the sum of all pids associated with all of the processes currently accessing the file is less than n. Define a monitor using the Hoare monitor model which coordinates access to the file given this constraint. You may assume that no pid is greater than n.


Deadlock

  1. Define deadlock.
  2. List the four necessary and sufficient conditions for deadlock.
  3. Is it possible to have a deadlock involving only one single process?
    If so, explain how. If not, explain why not.
  4. What is livelock? Compare and contrast it to deadlock.
  5. Give an example of a sharable resource in a computer system.
  6. Give an example of a non-sharable resource in a computer system.
  7. Write a complete Java program which when run may cause deadlock.
  8. Using quasicode, provide a complete example of a system with the possibility of deadlock.
  9. Java's locking mechanism is reentrant (i.e., if a thread acquires the lock for an object it can then enter other methods which require the lock for the same object). Explain how deadlock could occur if Java's locking mechanism was not reentrant.
  10. Consider the following resource allocation state snapshot of a system with 5 processes (p0, p1, p2, p3, p4) and 4 resource types (A, B, C, and D):

    process allocation   max   need   available  
      ABCD   ABCD   ABCD   ABCD  
    p0 0012 0012      1520
    p1 1000 1750          
    p2 1354 2356          
    p3 0632 0652          
    p4 0014 0656          
    • Fill in all entries of the need matrix above.
    • Is the system in a safe state?
    • Can a (0,4,2,0) request from process p1 be granted immediately?
  11. Consider the following resource allocation state snapshot of a system with 5 processes (p0, p1, p2, p3, p4) and 4 resource types (A, B, C, and D):

    process allocation   max   need   available  
      ABCD   ABCD   ABCD   ABCD  
    p0 1020 3242      3401
    p1 0312 3512          
    p2 2451 2775          
    p3 3006 5508          
    p4 4213 6214          
    • Fill in all entries of the need matrix above.
    • Is the system in a safe state?
    • Can a (0,4,0,1) request from process p3 be granted immediately?


Main memory management

  1. Define fragmentation. Differentiate between internal and external fragmentation.
  2. Fill in a yes or no in each of the following ten cells to indicate which of the following memory management techniques suffer from internal or external fragmentation. Do not consider wasted memory due to boundaries at powers of two to be internal fragmentation (e.g., a process of 4,095 bytes in a partition consisting of 212=4,096 bytes).

    technique internal external
    single contiguous    
    static partitions    
    dynamic partitions    
    paging    
    demand paging    

  3. Give the primary advantage of paged segmentation over pure paging.
  4. Given the following page table and a page size of 512 words, translate the relative address 1,053 to

    • a (page, word) pair
    • a (frame, word) pair
    • a physical address
    page frame
    0 12
    1 4
    2 3
    3 22
  5. List two distinct advantages to paging and one disadvantage.
  6. In a dynamic partition memory management scheme, a bounds register contains the value 4,025 and the base register contains the value 3,922. Give the physical address which is calculated from each of the following relative addresses.

    • 4,075
    • 3,988
    • 3,702
  7. How much total memory is required to store the page table on a computer with a 64-bit logical address space, a page size of 4k, where each page table entry occupies 4 bytes?

  8. At what time must logical addresses be bound to physical addresses to make compaction (i.e., defragmentation) possible?


Virtual Memory

  1. Define virtual memory and provide two benefits of it.
  2. Discuss how virtual memory differs from dynamic loading.

  3. What is the cause of thrashing? How does the system detect thrashing? Once thrashing is detected, what can the system do to eliminate the problem?

  4. Assume that a certain computer system uses demand-paged memory and that the page table is held in registers. Its takes 8 milliseconds (= 8,000,000 nanoseconds) to service a page fault if an empty frame is available or if the replaced page is not modified and 20 milliseconds (= 20,000,000 nanoseconds) if the replaced page is modified. Memory-access time is 100 nanoseconds. Assume that the page to be replaced is modified 70% of the time. What is the maximum acceptable page-fault rate for an effective memory access time of no more than 200 nanoseconds?

  5. Consider a demand paging system with a paging disk (swap space) which has an average access and transfer time of 20 milliseconds (= 20,000,000 nanoseconds). Addresses are translated through a page table in main memory, with an access time of 1 microsecond (= 1,000 nanoseconds) per memory access. To improve this time, we have added an associative cache memory which reduces access time to one memory reference if the page-table entry is in the cache (in other words, the cache takes no time to access). Assume that 80% of the accesses are in the cache and that, of those remaining, 10% (or 2% of the total) cause page faults. What is the effective memory access time? Be careful. Give your answer in nanoseconds.

  6. Give a reference string which demonstrates Belady's anomaly with the FIFO page replacement algorithm. For full credit, clearly demonstrate and describe how the string you provide exhibits the anomaly.

  7. The primary objective of main memory management is to pack as many processes as possible in main memory so to limit the amount of time the processor is idle. We discussed six approaches to this objective in class. List five of them.

  8. Discuss situations under which the least frequently used page-replacement algorithm generates fewer page faults than the least recently used page-replacement algorithm. Also discuss under what circumstances the opposite holds.

  9. What problem may occur with the following code?

    #include <stdio.h>
    #include <string.h>
    
    int main (int argc, char** argv) {
       char lastname[24];
    
       if (argc < 2) {
          fprintf (stderr, "USAGE: %s string\n", argv[0]);
          exit (1);
       }
    
       strcpy (lastname, argv[1]);
       exit (0);
    }
        

    Describe how you would need to modify this program to fix the problem and then show the corrected code.


References

    [CPL] B.W. Kernighan and D.M. Ritchie. The C Programming Language. Prentice Hall, Upper Saddle River, NJ, Second edition, 1988.
    [OSC] A. Silberschatz, P.B. Galvin, and G. Gagne. Operating Systems Concepts. John Wiley and Sons, Inc., Eighth edition, 2009.
    [OSCJ] A. Silberschatz, P.B. Galvin, and G. Gagne. Operating Systems Concepts with Java. John Wiley and Sons, Inc., Eighth edition, 2010.
    [OSIDP] W. Stallings. Operating Systems: Internals and Design Principles. Prentice Hall, Upper Saddle River, NJ, Sixth edition, 2009.
    [PGUS] M.G. Sobell. A Practical Guide to the UNIX System. Addison-Wesley, Reading, MA, Third edition, 1995.
    [UPE] B.W. Kernighan and R. Pike. The UNIX Programming Environment. Prentice Hall, Upper Saddle River, NJ, Second edition, 1984.
    [USP] K.A. Robbins and S. Robbins. UNIX Systems Programming: Concurrency, Communication, and Threads. Prentice Hall, Upper Saddle River, NJ, Second edition, 2003

Return Home