How fork() exit(0) and wait(NULL) works?

Viewed 1680

I'm trying to know how this code works

#include<stdio.h> 
#include<stdlib.h> 
#include<sys/wait.h> 
#include<unistd.h> 
  
int main() 
{ 
    pid_t cpid; 
    if (fork()== 0) 
        exit(0);         
    else
        cpid = wait(NULL); 
    printf("Parent pid = %d\n", getpid()); 
    printf("Child pid = %d\n", cpid); 
  
    return 0; 

(fork()==0) returns true if we're in the child process. Right?

Then exit(0) will terminate the child process.

Then how will wait(NULL) return the child pid if we can't enter the else case unless we're in a parent process?

2 Answers

The fork function creates a new processes and returns twice: once to the parent and once to the child.

In the child process, fork returns 0 so the if section runs which calls exit. In the parent process, fork returns the child's pid so it enters the else section where it calls wait which returns the pid of the child once the child exits.

I have a very good website for understand how use fork(), exit() and wait(). You can find a very good diagrams with code example.

forkcreate new processes, 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. the child process and parent process use the same PC(Program Counter).

Link for understand only fork:

https://www.geeksforgeeks.org/fork-system-call/

Link for understand fork with wait() and exit():

https://www.geeksforgeeks.org/wait-system-call-c/

If you don't understand I have GitHub repo where I use fork(), wait() and exit for create Linux Shell:

https://github.com/ClementBolin/Basic_Shell/blob/master/src/prompt/command.c https://github.com/ClementBolin/Basic_Shell/blob/master/src/prompt/execute_binary.c

Say me if you want to more information or example

Related