fork() in C - GeeksforGeeks (2024)

Table of Contents
CPP C C C C C C FAQs

Fork system call is used for creating a new process, which is called 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. A child process uses the same pc(program counter), same CPU registers, 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: 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 process ID of newly created child process. fork() in C - GeeksforGeeks (1)

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 Windows environment.

  1. Predict the Output of the following program:.

CPP

#include <stdio.h>

#include <sys/types.h>;

#include <unistd.h>;

int main()

{

// make two process which run same

// program after this instruction

fork();

printf("Hello world!\n");

return 0;

}

  1. Output:
Hello world!Hello world!
  1. Calculate number of times hello is printed:

C

#include <stdio.h>

#include <sys/types.h>

#include <unistd.h>

int main()

{

fork();

fork();

fork();

printf("hello\n");

return 0;

}

  1. Output:
hellohellohellohellohellohellohellohello
  1. The number of times ‘hello’ is printed is equal to number of process created. Total Number of Processes = 2n, where n is number of fork system calls. So here n = 3, 23 = 8 Let us put some label names for the three lines:
fork (); // Line 1fork (); // Line 2fork (); // Line 3 L1 // There will be 1 child process / \ // created by line 1. L2 L2 // There will be 2 child processes / \ / \ // created by line 2L3 L3 L3 L3 // There will be 4 child processes // created by line 3
  1. So there are total eight processes (new child processes and one original process). If we want to represent the relationship between the processes as a tree hierarchy it would be the following: The main process: P0 Processes created by the 1st fork: P1 Processes created by the 2nd fork: P2, P3 Processes created by the 3rd fork: P4, P5, P6, P7
 P0 / | \ P1 P4 P2 / \ \ P3 P6 P5 / P7
  1. Predict the Output of the following program:

C

#include <stdio.h>

#include <sys/types.h>;

#include <unistd.h>;

void forkexample()

{

// child process because return value zero

if (fork() == 0)

printf("Hello from Child!\n");

// parent process because return value non-zero.

else

printf("Hello from Parent!\n");

}

int main()

{

forkexample();

return 0;

}

  1. Output:
1.Hello from Child!Hello from Parent! (or)2.Hello from Parent!Hello from Child!
  1. In the above code, a child process is created. fork() returns 0 in the child process and positive integer in the parent process. Here, two outputs are possible because the parent process and child process are running concurrently. So we don’t know whether the OS will first give control to the parent process or the child process. Important: Parent process and child process are running the same program, but it does not mean they are identical. OS allocate different data and states for these two processes, and the control flow of these processes can be different. See next example:
  2. Predict the Output of the following program:

C

#include <stdio.h>

#include <sys/types.h>

#include <unistd.h>

void forkexample()

{

int x = 1;

if (fork() == 0)

printf("Child has x = %d\n", ++x);

else

printf("Parent has x = %d\n", --x);

}

int main()

{

forkexample();

return 0;

}

  1. Output:
Parent has x = 0Child has x = 2 (or)Child has x = 2Parent has x = 0
  1. Here, global variable change in one process does not affected two other processes because data/state of two processes are different. And also parent and child run simultaneously so two outputs are possible.

fork() vs exec()

The fork system call creates a new process. The new process created by fork() is a copy of the current process except for the returned value. The exec() system call replaces the current process with a new program. Exercise:

  1. A process executes the following code:

C

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

fork();

  1. 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 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);

}

  1. 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 solution.
  2. Predict output of below program.

C

#include <stdio.h>

#include <unistd.h>

int main()

{

fork();

fork() && fork() || fork();

fork();

printf("forked\n");

return 0;

}

  1. See this for solution

Related Articles : C program to demonstrate fork() and pipe() Zombie and Orphan Processes in C fork() and memory shared b/w processes created using it. References: http://www.csl.mtu.edu/cs4411.ck/www/NOTES/process/fork/create.html This article is contributed by Team GeeksforGeeks and Kadam Patel. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks 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.


My Personal Notesarrow_drop_up

fork() in C - GeeksforGeeks (2024)

FAQs

What does fork() do in C? ›

The fork() function creates a new process. The new process (child process) is an exact copy of the calling process (parent process) except as detailed below. The child process has a unique process ID. The child process ID also does not match any active process group ID.

What does fork() return? ›

The C fork() function returns a zero value to the child process that is newly created. On successful duplication of a process, the PID of the child process is returned in the parent, and 0 is returned in the child process.

What is fork () and exec () in C? ›

fork starts a new process which is a copy of the one that calls it, while exec replaces the current process image with another (different) one. Both parent and child processes are executed simultaneously in case of fork() while Control never returns to the original program unless there is an exec() error.

Where is fork () used? ›

The fork() system call is used in Unix-based OS to create a new process by duplicating the calling process. The new process is an exact copy of the parent process, with its own address space and memory.

Why is fork () useful? ›

In multitasking operating systems, processes (running programs) need a way to create new processes, e.g. to run other programs. Fork and its variants are typically the only way of doing so in Unix-like systems. For a process to start the execution of a different program, it first forks to create a copy of itself.

How to use fork() in C in Windows? ›

  1. You can't use fork() in a Windows environment, it is is only present in the standard libraries on Unix or Linux based operating systems.
  2. The Windows C equivalent are the various spawn() functions.
  3. Or if you want to do it at a lower level use the WINAPI call CreateProcess()
Jan 10, 2017

Why does Fork() return twice? ›

The fork() creates a copy of the process that was executing. The fork() is called once but returns twice (once in the parent and once in the child). The line PID = fork(); returns the value of the fork() system call. The if (PID == 0) evaluates the return value.

What happens when you call a fork () in a thread? ›

If a multi-threaded process calls fork(), the new process shall contain a replica of the calling thread and its entire address space, possibly including the states of mutexes and other resources.

Why does fork return 0 to the child process? ›

fork() returns 0 to the child process to indicate that it is the child. If the child wants to figure out its own PID, it can call getpid() , and if the child wants to figure out the parent process's PID, it can call getppid() . fork() returns the child process's PID (a positive number) to the parent.

Why exec is used after fork? ›

The child process created via the fork() system call is always similar to its parent process. They both coexist. The child process created via the exec() system call replaces its parent process. Since the parent and child process coexist after the fork() system call, they reside in different address spaces.

What is the purpose of fork() and exec() system call? ›

The fork() returns the PID of the child process. If the value is non-zero, then it is parent process's id, and if this is 0, then this is child process's id. The exec() system call is used to replace the current process image with the new process image.

What is exec () in C? ›

The exec family of functions replaces the current running process with a new process. It can be used to run a C program by using another C program. It comes under the header file unistd.

What will fork () return? ›

If successful, fork() returns 0 to the child process and the process ID of the newly created child to the parent process. If unsuccessful, fork() fails to create a child process, returns -1 to the parent, and sets errno to one of the following values: Error Code.

What is fork () used for? ›

The purpose of fork() is to create a new process, which becomes the child process of the caller. After a new child process is created, both processes will execute the next instruction following the fork() system call.

How many processes are created by fork? ›

Each fork call duplicate process, so after first call there are two of them. You may call the one with pid = 0, the master process (parent, top, original). After that two processes are in the second line (second fork), executing it, there are four processes now.

What is the purpose of a fork? ›

fork, implement consisting of two or more prongs supported by a handle, used for cooking, serving, and eating food. Forks and spoons together are known as flatware (q.v.).

What is fork used for in programming? ›

A fork is a new repository that shares code and visibility settings with the original “upstream” repository. Forks are often used to iterate on ideas or changes before they are proposed back to the upstream repository, such as in open source projects or when a user does not have write access to the upstream repository.

What does wait() do in C? ›

The wait() function will suspend execution of the calling thread until status information for one of its terminated child processes is available, or until delivery of a signal whose action is either to execute a signal-catching function or to terminate the process.

How does fork return two values? ›

The fork() creates a copy of the process that was executing. The fork() is called once but returns twice (once in the parent and once in the child). The line PID = fork(); returns the value of the fork() system call. The if (PID == 0) evaluates the return value.

Top Articles
Introduction to Final Accounts and Accounting Treatment
What is Rosetta API? - Electra Protocol
Express Pay Cspire
Tyler Sis 360 Louisiana Mo
Dragon Age Inquisition War Table Operations and Missions Guide
Bild Poster Ikea
Encore Atlanta Cheer Competition
O'reilly's In Monroe Georgia
Pike County Buy Sale And Trade
Jasmine
Snarky Tea Net Worth 2022
Tv Schedule Today No Cable
2013 Chevy Cruze Coolant Hose Diagram
Craigslist Jobs Phoenix
Eka Vore Portal
Cvs Appointment For Booster Shot
Rams vs. Lions highlights: Detroit defeats Los Angeles 26-20 in overtime thriller
Geometry Review Quiz 5 Answer Key
Marine Forecast Sandy Hook To Manasquan Inlet
Military life insurance and survivor benefits | USAGov
Contracts for May 28, 2020
Betaalbaar naar The Big Apple: 9 x tips voor New York City
How Long After Dayquil Can I Take Benadryl
The Creator Showtimes Near R/C Gateway Theater 8
Meet the Characters of Disney’s ‘Moana’
Access a Shared Resource | Computing for Arts + Sciences
Trinket Of Advanced Weaponry
Riverstock Apartments Photos
Rek Funerals
Askhistorians Book List
Bad Business Private Server Commands
Pickle Juiced 1234
Rise Meadville Reviews
Frostbite Blaster
Western Gold Gateway
Why Holly Gibney Is One of TV's Best Protagonists
Cdcs Rochester
Cheetah Pitbull For Sale
Cookie Clicker The Advanced Method
Pokemon Reborn Gyms
COVID-19/Coronavirus Assistance Programs | FindHelp.org
Www Craigslist Com Atlanta Ga
Swsnj Warehousing Inc
Server Jobs Near
Kushfly Promo Code
Gummy Bear Hoco Proposal
Strawberry Lake Nd Cabins For Sale
Uncle Pete's Wheeling Wv Menu
Public Broadcasting Service Clg Wiki
Electronics coupons, offers & promotions | The Los Angeles Times
Latest Posts
Article information

Author: Kareem Mueller DO

Last Updated:

Views: 6259

Rating: 4.6 / 5 (66 voted)

Reviews: 81% of readers found this page helpful

Author information

Name: Kareem Mueller DO

Birthday: 1997-01-04

Address: Apt. 156 12935 Runolfsdottir Mission, Greenfort, MN 74384-6749

Phone: +16704982844747

Job: Corporate Administration Planner

Hobby: Mountain biking, Jewelry making, Stone skipping, Lacemaking, Knife making, Scrapbooking, Letterboxing

Introduction: My name is Kareem Mueller DO, I am a vivacious, super, thoughtful, excited, handsome, beautiful, combative person who loves writing and wants to share my knowledge and understanding with you.