CS 105

Files and File Descriptors

File System Calls and File Descriptors

Consider this code:

#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>

int main() {
    int fd1 = open("myfile.txt", O_WRONLY|O_CREAT|O_TRUNC, 0644);
    int fd2 = dup(fd1);
    int fd3 = open("myfile.txt", O_RDONLY);
    int fd4 = open("myfile.txt", O_RDONLY);
    char buf[6] = {0}; // Initialize buffer to all zeros

    write(fd1, "Hello", 5);
    write(fd2, "World", 5);
    read(fd3, buf, 5);
    printf("Read from fd3: %s\n", buf);
    read(fd4, buf, 5);
    printf("Read from fd4: %s\n", buf);

    return 0;
}

How many VFS-layer file objects are accessed by this program's code? (Note, this is not asking about open file descriptions, but rather the higher-level VFS objects that represent files inside the kernel.)

How many internal “open-file” objects are created by this program's code? (These are the kernel objects that represent an open file, and they include a file offset, allowed access mode (read or write), and a pointer to the VFS-layer file object, as well as a reference count indicating how many file descriptors refer to it.)

In addition to the standard three file descriptors (0 for stdin, 1 for stdout, and 2 for stderr), how many extra file descriptors are open at the end of this program?

Write exactly the text we'll find in myfile.txt after this program runs.

What will the code print, and why?

How would the program's behavior change if we added a call to fork() right after the first printf call? (Assume output is line-buffered, so all prints happen immediately.)

If there is more than one possible behavior, describe all of them. Explain your answer.

(When logged in, completion status appears here.)