309 views
4 4 votes

Assume that every $\texttt{fork()}$ call succeeds.

int main() {
    int pid;

    pid = fork() && fork();

    if (!pid)
        printf("A\n");
    else
        printf("B\n");

    return 0;
}

How many times are $\texttt{A}$ and $\texttt{B}$ printed, respectively?

  1. $\texttt{A}$ is printed once and $\texttt{B}$ is printed once
     
  2. $\texttt{A}$ is printed once and $\texttt{B}$ is printed twice
     
  3. $\texttt{A}$ is printed twice and $\texttt{B}$ is printed once
     
  4. $\texttt{A}$ is printed twice and $\texttt{B}$ is printed twice

1 Answer

0 0 votes

The expression uses the logical AND operator:

$\texttt{fork() \&\& fork()}$

The second $\texttt{fork()}$ is evaluated only when the first operand is nonzero.

For the first $\texttt{fork()}$ :

  • The parent receives a positive value, so it executes the second $\texttt{fork()}$.
     
  • The child receives $0$, so short-circuit evaluation prevents it from executing the second $\texttt{fork()}$.

The parent that executes the second $\texttt{fork()}$ produces:

  • One parent for which the complete expression is true
     
  • One child for which the second $\texttt{fork()}$ returns $0$

Therefore, there are three processes:

  • First child $: \texttt{pid = 0}$, prints $\texttt{A}$
     
  • Second child $: \texttt{pid = 0}$, prints $\texttt{A}$
     
  • Original parent $:\texttt{pid = 1}$, prints $\texttt{B}$

Thus, $\texttt{A}$ is printed twice and $\texttt{B}$ is printed once.

Answer : C

Answer:
Position:
Show:

Related questions

5 5 votes
2 2 answers
457
457 views
GO Classes asked Jul 15
457 views
Consider the following C program. Assume that every $\texttt{fork()}$ call succeeds.int main(void) { unsigned long int i; for (i = 0; i < 6; i++) if (fork() >= 0) continu...
3 3 votes
1 1 answer
313
313 views
GO Classes asked Jul 15
313 views
Assume that every $\texttt{fork()}$ call succeeds.int main() { int a = 0; int rc = fork(); a++; if (rc == 0) { rc = fork(); a++; } else { a++; } printf("a is %d\n", a); }...
5 5 votes
1 1 answer
290
290 views
GO Classes asked Jul 15
290 views
Consider the following program. Assume that every $\texttt{fork()}$ call succeeds.int main() { int p1 = 1, p2 = 2, p3 = 3; p1 = fork(); if (p2 0) p2 = fork(); if (p1 0)...
5 5 votes
2 2 answers
269
269 views
GO Classes asked Jul 15
269 views
Consider the following C program. When the execution reaches line $5$, how many processes and threads, respectively, exist in the process hierarchy?int main() { int i; fo...