Question 1#

Consider the C program below. (For space reasons, we are not checking error return codes, so assume that all functions return normally.)

main() {
    if (fork() == 0) {
        if (fork() == 0) {
            printf("2");
        }
        else {
            pid_t pid; int status;
            if ((pid = wait(&status)) > 0) {
                printf("3");
            }
        }
    }
    else {
        if (fork() == 0) {
            printf("5");
            exit(0);
        }
        printf("4");
    }
    printf("0");
    return 0;
}

A#

Sketch the process graph for the above program showing the ordering of program statements.

B#

List all feasible outputs possible as a result of executing the above C program.

C#

List two outputs (i.e., ordering of printf statements) that are not possible as a result of running the above C program.

Question 2#

Consider the following C program. (For space reasons, we are not checking error return codes, so assume that all functions return normally.)

pid_t pid;

void handler1(int sig) {
    printf("sting");
    fflush(stdout); /* Flushes the printed string to stdout */
    kill(pid, SIGUSR1);
}

void handler2(int sig) {
    printf("radiohead");
    exit(0);
}

main() {
    signal(SIGUSR1, handler1);
    if ((pid = fork()) == 0) {
        signal(SIGUSR1, handler2);
        kill(getppid(), SIGUSR1);
        while(1) {};
    }
    else {
        pid_t p; int status;
        if ((p = wait(&status)) > 0) {
            printf("nirvana");
        }
    }
}

What is the output string that the above program prints?

Note # 1: The SIGUSR1 and SIGUSR2 signals are set aside for programmers to use any way they want. They are useful for simple interprocess communication. Programmers write signal handlers for them in the program that receive the signals.

Note # 2: The C library function int fflush(FILE *stream) flushes the output buffer of a stream. Recall from Week 7 lectures that three file descriptors (0,1,2) and three FILE streams (stdin, stdout, stderr) are associated with each Linux process by default.

bars search times arrow-up