Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • 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
  • 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++
Open In App
Next Article:
Difference between fork() and exec()
Next article icon

Difference between fork() and exec()

Last Updated : 08 Nov, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

Every application(program) comes into execution through means of process, process is a running instance of a program. Processes are created through different system calls, most popular are fork() and exec()

fork()

pid_t pid = fork();

fork() creates a new process by duplicating the calling process, The new process, referred to as child, is an exact duplicate of the calling process, referred to as parent, except for the following :

  1. The child has its own unique process ID, and this PID does not match the ID of any existing process group.
  2. The child's parent process ID is the same as the parent's process ID.
  3. The child does not inherit its parent's memory locks and semaphore adjustments.
  4. The child does not inherit outstanding asynchronous I/O operations from its parent nor does it inherit any asynchronous I/O contexts from its parent.

Return value of fork() On success, the PID of the child process is returned in the parent, and 0 is returned in the child. On failure, -1 is returned in the parent, no child process is created, and errno is set appropriately.

exec()

The exec() family of functions replaces the current process image with a new process image. It loads the program into the current process space and runs it from the entry point. The exec() family consists of following functions, I have implemented execv() in following C program, you can try rest as an exercise

int execl(const char *path, const char *arg, ...); int execlp(const char *file, const char *arg, ...); int execle(const char *path, const char *arg, ...,                                 char * const envp[]); int execv(const char *path, char *const argv[]); int execvp(const char *file, char *const argv[]); int execvpe(const char *file, char *const argv[],                                char *const envp[]);

fork vs exec

  • 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.
C
// C program to illustrate use of fork() & // exec() system call for process creation  #include <stdio.h> #include <sys/types.h> #include <unistd.h>  #include <stdlib.h> #include <errno.h>  #include <sys/wait.h>  int main(){ pid_t pid; int ret = 1; int status; pid = fork();  if (pid == -1){      // pid == -1 means error occurred     printf("can't fork, error occurred\n");     exit(EXIT_FAILURE); } else if (pid == 0){      // pid == 0 means child process created     // getpid() returns process id of calling process     // Here It will return process id of child process     printf("child process, pid = %u\n",getpid());     // Here It will return Parent of child Process means Parent process it self     printf("parent of child process, pid = %u\n",getppid());       // the argv list first argument should point to      // filename associated with file being executed     // the array pointer must be terminated by NULL      // pointer     char * argv_list[] = {"ls","-lart","/home",NULL};      // the execv() only return if error occurred.     // The return value is -1     execv("ls",argv_list);     exit(0); } else{     // a positive number is returned for the pid of     // parent process     // getppid() returns process id of parent of      // calling process // Here It will return parent of parent process's ID     printf("Parent Of parent process, pid = %u\n",getppid());     printf("parent process, pid = %u\n",getpid());           // the parent process calls waitpid() on the child         // waitpid() system call suspends execution of          // calling process until a child specified by pid         // argument has changed state         // see wait() man page for all the flags or options         // used here          if (waitpid(pid, &status, 0) > 0) {                          if (WIFEXITED(status) && !WEXITSTATUS(status))              printf("program execution successful\n");                          else if (WIFEXITED(status) && WEXITSTATUS(status)) {                 if (WEXITSTATUS(status) == 127) {                      // execv failed                     printf("execv failed\n");                 }                 else                     printf("program terminated normally,"                     " but returned a non-zero status\n");                          }             else             printf("program didn't terminate normally\n");                  }          else {         // waitpid() failed         printf("waitpid() failed\n");         }     exit(0); } return 0; } 

Output:

parent process, pid = 11523 child process, pid = 14188 Program execution successful

Let us see the differences in a tabular form -:

 fork()exec()
1.It is a system call in the C programming languageIt is a system call of operating system
2.It is used to create a new processexec() runs an executable file
3.Its return value is an integer typeIt does not creates new process
4.It does not takes any parameters.Here the Process identifier does not changes
5.It can return three types of integer valuesIn exec() the machine code, data, heap, and stack of the process are replaced by the new program.


Next Article
Difference between fork() and exec()

M

Mandeep Singh
Improve
Article Tags :
  • Misc
  • Difference Between
  • C Language
  • system-programming
Practice Tags :
  • Misc

Similar Reads

    Difference between fork() and vfork()
    1. fork() : Fork() is system call which is used to create new process. New process created by fork() system call is called child process and process that invoked fork() system call is called parent process. Code of child process is same as code of its parent process. Once child process is created, b
    2 min read
    Difference between Program and Executable File
    1. Program : Program, as name suggest, are simply set of instructions developed by programmer that tell computer what to perform and consist of compiled code that run directly from operating system of computer. 2. Executable File : Executable File, as name suggests, are computer files that contain e
    2 min read
    Difference between system() and execl() call
    A system() call is a way for the programs to interact with the operating system. It is used to execute a command within a process. The system call provides the services of the operating system to the user programs via Application Program Interface (API). It provides an interface between a process an
    4 min read
    Difference between Program and Process
    In Computer Science, there are two fundamental terms in operating system: Program and Process. Program is a set of instructions written to perform a task, stored in memory. A process is the active execution of a program, using system resources like CPU and memory. In other words, a program is static
    4 min read
    Difference Between fork and clone in GitHub
    Understanding the difference between fork and clone in GitHub is important for anyone looking to collaborate on open-source projects or manage their code efficiently. While both actions involve creating a copy of a repository, their purposes and implementations differ significantly. This article wil
    3 min read
geeksforgeeks-footer-logo
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
GFG App on Play Store GFG App on App Store
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
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
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