Lab 2 Solutions

These questions were written by Jerry Cain and Ryan Eberhardt.

Problem 1: Virtual Memory

Assume the OS allocates virtual memory to physical memory in 4096-byte pages.

For fun, optional reading, read these two documents (though you needn’t do this reading, since it goes beyond the scope of my lecture discussion of virtual memory):

Problem 2: File descriptors

  1. Consider the following code:
    int main() {
        int fd = open("/cplayground/code.cpp", O_RDONLY);
        printf("Using file descriptor %d\n", fd);
       
        // Try reading some bytes:
        char buf[16];
        ssize_t num_read = read(fd, buf, sizeof(buf));
        printf("Read %ld bytes\n", num_read);
       
        // Close file descriptor
        close(fd);
    }
    
    1. What does open do to the file descriptor, open file, and vnode tables? What about read? What about close?

      Open this Cplayground and press “Debug” to start the program. Navigate to the “Open Files” tab to see a visualization of the three tables. Try stepping through the code line-by-line to confirm your intuition.

      • open: creates new entries in the vnode, open file, and file descriptor tables
      • read: advances the cursor in the open file table
      • close: removes the file descriptor, which in turn removes the open file table entry, which in turn removes the vnode table entry
    2. What happens to the file descriptor, open file, and vnode tables if you add an extra open call?

      int fd = open("/cplayground/code.cpp", O_RDONLY);
      int fd2 = open("/cplayground/code.cpp", O_RDONLY);
      

      Use Cplayground to confirm your intuition.

      • The second open call creates a new entry in the open file table. (As long as open succeeds, this will always be true. Conceptually, open is creating a new session, and the open file table stores sessions.) This also causes the refcount to be incremented in the vnode table, and of course, a new file descriptor is created to point to this new session.
  2. The dup system call accepts a valid file descriptor, claims a new, previously unused file descriptor, configures that new descriptor to alias the same file session as the incoming one, and then returns it. Briefly outline what happens to the relevant open file table and vnode table entries as a result of dup being called. (Read man dup if you’d like, though don’t worry about error scenarios).
    • The vnode table entry is left alone, but a new file descriptor is claimed and set to address the same entry in the open file table session as the incoming one, and the reference count within that session entry would be incremented by one.

Problem 3: Creating processes