in Operating System retagged by
779 views
5 votes
5 votes

Assume the following code is compiled and run on a modern Linux machine.

Assuming $\textsf{fork()}$ never fails, how many times will the message $\textsf{“Hello”}$ will be displayed?

#include <stdio.h>
#include <unistd.h>
int main() {
    int a = 0;
    int rc = fork();
    if (rc == 0) {
        rc = fork();
    } else {
        printf("Hello");
    }
    printf("Hello");
    return 0;
}
  1. $2$
  2. $3$
  3. $4$
  4. $6$
in Operating System retagged by
779 views

2 Answers

2 votes
2 votes

The program starts and enters the main() function.

The variable a is declared and initialized to 0.

The fork() system call is invoked, creating a new process. Let's call the original process "Process A" and the newly created process "Process B."

In Process A, the value of rc is not equal to 0, so it proceeds to the else block and prints "Hello."

Process A continues execution and reaches the second printf("Hello") statement, resulting in another "Hello" message being printed by Process A.

In Process B, the value of rc is equal to 0, so it enters the if statement.

Inside the if block of Process B, another fork() is called, creating a new process. Let's call this newly created process "Process C."

Process B, does not enter the else block and proceeds and reaches the second printf("Hello") statement and prints "Hello."

Process C, being the child process of Process B, does not enter the if statement and does not enter the else block because it is created within the if block of Process B. C proceeds and reaches the second printf("Hello") statement and prints "Hello."

Process A, Process B, and Process C exit the main() function, and the program terminates.

Therefore, Process A prints "Hello" twice, while Process B and Process C each print "Hello" once.

3 Comments

“In Process B, the value of rc is equal to 0”, can you please explain this?

0
0

Upon successful completion, fork() returns 0 to the child process and returns the process ID of the child process to the parent process. Otherwise, -1 is returned to the parent process, no child process is created, and errno is set to indicate the error.

0
0

 whenever a fork is called using a variable, fork() system call returns 0 in the child process to distinguish it from the parent process,

0
0
0 votes
0 votes
upon successful exceution fork() returns 0 to child processes and processID to parent process. so the else case will never be executed. meanwhile 1 becomes 2 and 2 become 4 due to fork(). so 4 times HELLO will be printed.
Answer:

Related questions