Problems based on C fork()

1. A process executes the following code

C




for (i = 0; i < n; i++)
    fork();


The total number of child processes created is (GATE-CS-2008)

(A) n 
(B) 2^n – 1
(C) 2^n
(D) 2^(n+1) – 1

See this for a solution.

2. Consider the following code fragment: 

C




if (fork() == 0) {
    a = a + 5;
    printf("%d, %d\n", a, &a);
}
else {
    a = a –5;
    printf("%d, %d\n", a, &a);
}


Let u, v be the values printed by the parent process, and x, y be the values printed by the child process. Which one of the following is TRUE? (GATE-CS-2005)

(A) u = x + 10 and v = y
(B) u = x + 10 and v != y
(C) u + 10 = x and v = y
(D) u + 10 = x and v != y

See this for a solution.

3. Predict the output of the below program.

C




#include <stdio.h>
#include <unistd.h>
int main()
{
    fork();
    fork() && fork() || fork();
    fork();
  
    printf("forked\n");
    return 0;
}


See this for the solution

Related Articles :

This article is contributed by Team w3wiki and Kadam Patel. If you like w3wiki and would like to contribute, you can also write an article using write.w3wiki.org or mail your article to review-team@w3wiki.org. See your article appearing on the w3wiki main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.



fork() in C

The Fork system call is used for creating a new process in Linux, and Unix systems, which is called the child process, which runs concurrently with the process that makes the fork() call (parent process). After a new child process is created, both processes will execute the next instruction following the fork() system call.

The child process uses the same pc(program counter), same CPU registers, and same open files which use in the parent process. It takes no parameters and returns an integer value.

Below are different values returned by fork().

  • Negative Value: The creation of a child process was unsuccessful.
  • Zero: Returned to the newly created child process.
  • Positive value: Returned to parent or caller. The value contains the process ID of the newly created child process.

Note: fork() is threading based function, to get the correct output run the program on a local system.

Please note that the above programs don’t compile in a Windows environment.

Similar Reads

Example of fork() in C

C #include #include #include int main() {        // make two process which run same     // program after this instruction     pid_t p = fork();     if(p<0){       perror("fork fail");       exit(1);     }     printf("Hello world!, process_id(pid) = %d \n",getpid());     return 0; }...

Problems based on C fork()

...