Что такое форк в программировании - Журнал «Код TheFork is the leading online restaurant booking and discovery platform in Europe and Australia. Discover more than 60,000 of the best dining spots across ...
FORK - Перевод на русский - bab.la From your web browser, navigate to the Azure Repos Git repo that you want to fork. Select Repo > Files and then choose Fork from the ellipsis ...
Fork - Wikipedia fork() creates a new process by duplicating the calling process. The new process is referred to as the child process. The calling process is referred to as the ...
fork - Wiktionary, the free dictionary Why Wild Fork? We offer the widest selection of high-quality meat and seafood at the lowest everyday prices. What's our secret? Blast freezing at the peak of ...
TheFork: Book the best restaurants in Europe Attract new customers and manage restaurant reservations with TheFork Manager, the complete online restaurant reservation and restaurant management sofware.
Skip to content Courses DSA to Development Get IBM Certification Newly Launched! Master Django Framework Become AWS Certified For Working Professionals Interview 101: DSA & System Design Data Science Training Program JAVA Backend Development (Live) DevOps Engineering (LIVE) Data Structures & Algorithms in Python For Students Placement Preparation Course Data Science (Live) Data Structure & Algorithm-Self Paced (C++/JAVA) Master Competitive Programming (Live) Full Stack Development with React & Node JS (Live) Full Stack Development Data Science Program All Courses Tutorials Data Structures & Algorithms ML & Data Science Interview Corner Programming Languages Web Development CS Subjects DevOps And Linux School Learning Practice Build your AI Agent GfG 160 Problem of the Day Practice Coding Problems GfG SDE Sheet Contests Accenture Hackathon (Ending Soon!) GfG Weekly [Rated Contest] Job-A-Thon Hiring Challenge All Contests and Events C C Basics C Data Types C Operators C Input and Output C Control Flow C Functions C Arrays C Strings C Pointers C Preprocessors C File Handling C Programs C Cheatsheet C Interview Questions C MCQ C++ Sign In ▲ Open In App Next Article: fgets() in C
fork() in C
Last Updated : 12 May, 2025 Comments Improve Suggest changes Like Article Like Report
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, then it returns -1. 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.
Also, if you’re interested in understanding process control and memory allocation in C, the C Programming Course Online with Data Structures covers these topics in depth.
Please note that the below programs don’t compile in a Windows environment.
Example of fork() in C
C #include stdio.h #include sys/types.h #include unistd.h 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 ; } Output Hello world!, process_id(pid) = 31 Hello world!, process_id(pid) = 32
Example 2: Calculate the number of times hello is printed.
The number of times ‘hello’ is printed is equal to the number of processes created. Total Number of Processes = 2 n , where n is the number of fork system calls. So here n = 3, 2 3 = 8 Let us put some label names for the three lines:
fork (); // Line 1 fork (); // Line 2 fork (); // Line 3 L1 // There will be 1 child process / \ // created by line 1. L2 L2 // There will be 2 child processes / \ / \ // created by line 2 L3 L3 L3 L3 // There will be 4 child processes // created by line 3
So there is a total of 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:
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
Example 3: Predict the Output of the following program.
C #include stdio.h #include stdlib.h #include sys/types.h #include unistd.h void forkexample () { pid_t p ; p = fork (); if ( p 0 ) { perror ( fork fail ); exit ( 1 ); } // child process because return value zero else if ( p == 0 ) printf ( Hello from Child! \n ); // parent process because return value non-zero. else printf ( Hello from Parent! \n ); } int main () { forkexample (); return 0 ; } Output Hello from Parent! Hello from Child!
Note: 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.
Parent process and child process are running the same program, but it does not mean they are identical. OS allocates different data and states for these two processes, and the control flow of these processes can be different. See the next example:
Example 4: Predict the Output of the following program.
C #include stdio.h #include stdlib.h #include sys/types.h #include unistd.h void forkexample () { int x = 1 ; pid_t p = fork (); if ( p 0 ){ perror ( fork fail ); exit ( 1 ); } else if ( p == 0 ) printf ( Child has x = %d \n , ++ x ); else printf ( Parent has x = %d \n , -- x ); } int main () { forkexample (); return 0 ; } Output Parent has x = 0 Child has x = 2
or
Output
Child has x = 2 Parent has x = 0
Here, global variable change in one process does not affect two other processes because the data/state of the two processes is 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. On the other hand, the exec() system call replaces the current process with a new program.
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 :
C program to demonstrate fork() and pipe() Zombie and Orphan Processes in C fork() and memory shared b/w processes created using it
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.
Comment More info Advertise with us Next Article fgets() in C
K
Kadam Patel Improve Article Tags : C Language C-Library system-programming
Similar Reads
fwrite() in C In C, fwrite() is a built-in function used to write a block of data from the program into a file. It can write arrays, structs, or other data to files but is especially designed to write binary data in binary files. Example: [GFGTABS] C #include stdio.h int main() { FILE *fptr = fopen(" 3 min read fgets() in C In C, fgets() is a built-in function defined in stdio.h header file. It reads the given number of characters of a line from the input stream and stores it into the specified string. This function stops reading the characters when it encounters a newline character, has read the given number o 4 min read Fork() Bomb Prerequisite : fork() in CFork Bomb is a program that harms a system by making it run out of memory. It forks processes infinitely to fill memory. The fork bomb is a form of denial-of-service (DoS) attack against a Linux based system.Once a successful fork bomb has been activated in a system it may 3 min read gets() in C In C, gets() is a function used to read a line of input from standard input (stdin) into a character array. However, gets() has been deprecated since C11 and removed in later standards due to its unsafe behaviour, such as not limiting the number of characters read, which can lead to buffer overflows 3 min read C - File I/O In this article, we will learn how to operate over files using a C program. A single C file can read, write, move, and create files in our computer easily using a few functions and elements included in the C File I/O system. We can easily manipulate data in a file regardless of whether the file is a 11 min read C String Functions C language provides various built-in functions that can be used for various operations and manipulations on strings. These string functions make it easier to perform tasks such as string copy, concatenation, comparison, length, etc. The string.h header file contains these string functions. T 7 min read Format Specifiers in C The format specifier in C is used to tell the compiler about the type of data to be printed or scanned in input and output operations. They always start with a % symbol and are used in the formatted string in functions like printf(), scanf, sprintf(), etc. The C language provides a number of format 6 min read C vs BASH Fork bomb Pre-requisites : Fork System Call Fork bomb Bash fork bomb : :(){:&:&};: Working in Unix : In Unix-like operating systems, fork bombs are generally written to use the fork system call. As forked processes are also copies of the first program, once they resume execution from the next address 3 min read rewind() in C In C, rewind() is a built-in function used to reset the given file pointer to the beginning of a file allowing the read and write from the beginning once again in the program without reopening the file. Example: [GFGTABS] C #include stdio.h int main() { FILE *fptr = fopen("file.txt 3 min read Tokens in C In C programming, tokens are the smallest units in a program that have meaningful representations. Tokens are the building blocks of a C program, and they are recognized by the C compiler to form valid expressions and statements. Tokens can be classified into various categories, each with specific r 4 min read Like Corporate & Communications Address: A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305) Registered Address: K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305 Advertise with us Company About Us Legal Privacy Policy In Media Contact Us Advertise with us GFG Corporate Solution Placement Training Program Languages Python Java C++ PHP GoLang SQL R Language Android Tutorial Tutorials Archive DSA Data Structures Algorithms DSA for Beginners Basic DSA Problems DSA Roadmap Top 100 DSA Interview Problems DSA Roadmap by Sandeep Jain All Cheat Sheets Data Science & ML Data Science With Python Data Science For Beginner Machine Learning ML Maths Data Visualisation Pandas NumPy NLP Deep Learning Web Technologies HTML CSS JavaScript TypeScript ReactJS NextJS Bootstrap Web Design Python Tutorial Python Programming Examples Python Projects Python Tkinter Python Web Scraping OpenCV Tutorial Python Interview Question Django Computer Science Operating Systems Computer Network Database Management System Software Engineering Digital Logic Design Engineering Maths Software Development Software Testing DevOps Git Linux AWS Docker Kubernetes Azure GCP DevOps Roadmap System Design High Level Design Low Level Design UML Diagrams Interview Guide Design Patterns OOAD System Design Bootcamp Interview Questions Inteview Preparation Competitive Programming Top DS or Algo for CP Company-Wise Recruitment Process Company-Wise Preparation Aptitude Preparation Puzzles School Subjects Mathematics Physics Chemistry Biology Social Science English Grammar Commerce World GK GeeksforGeeks Videos DSA Python Java C++ Web Development Data Science CS Subjects @GeeksforGeeks, Sanchhaya Education Private Limited , All rights reserved We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy Got It ! Improvement Suggest changes Suggest Changes Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal. Create Improvement Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all. Suggest Changes min 4 words, max Words Limit:1000
Thank You!
Your suggestions are valuable to us.
What kind of Experience do you want to share?
Interview Experiences Admission Experiences Career Journeys Work Experiences Campus Experiences Competitive Exam Experiences