CS 105

Processes etc.

Processes and Concurrency

Consider the following C program:

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

int main() {
    char* words[] = {"Let's", "go", "CS", "105!"};
    for (int i = 0; i < 4; ++i) {
        pid_t pid = fork();
        if (pid == 0) {
            printf("%s ", words[i]);
            return i+1;
        }
    }

    sleep(2);

    printf("\nBye!\n");

    return 0;
}

When considering this code, assume that the fork system call always succeeds, that the scheduler can interleave the execution of the parent and child processes in any way, and that the children run quickly enough that they will be done by the time the parent wakes up from sleep.

If any part suggests a change to the program, the program is reset to its original form before the next part.

What can you say about this program? Check all that apply:

Suppose we change the return i+1; in the child process to exit(i+1);. How does this change the behavior of the program?

Suppose we remove the sleep(2); call. How does this change the behavior of the program?

Suppose we add waitpid(pid, NULL, 0); in an else block for the if statement that checks pid == 0. How does this change the behavior of the program?

Suppose we remove the return i+1; line from the child process and add this line instead:

fflush(stdout);

How does this change the behavior of the program? Include a description of what gets printed and why.

In the previous part, we removed the return i+1; line from the child process and added fflush(stdout);. If you remove the return line but don't include the fflush(stdout); line, how does the behavior change?

(When logged in, completion status appears here.)