4

What is the reason for the code result? And what happens when an exception happens in the fork()?

#include<stdio.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/wait.h>
int main(){
    int pid=fork();
    if(pid==0){
        int child=getpid();
        printf("child: parent %d\n",getppid());
        sleep(4);
        printf("child: parent %d\n",getppid());
        sleep(100);
    }
    else{
        int parent=getpid();
        printf("parent: parent %d\n",getppid());
        sleep(2);
        int zero=0;
        int i=3/zero;
    }
    return 0;
}

And here's the output:

parent: parent 63742
child: parent 63825
Floating point exception (core dumped)
ubunto@ubuntu:~/Desktop$ child: parent 4497
Roberto Caboni
  • 7,252
  • 10
  • 25
  • 39

1 Answers1

0

Here it is the time sequence of the execution:

Second 0:

  1. fork() issued
  2. The parent process prints its pid (63742)
  3. The child process prints its pid (63825)
  4. Both processes issue a sleep

Second 1:

  • Both processes are sleeping

Second 2:

  1. Parent process wakes up. Child process will sleep for 2 further seconds
  2. Parent process issues a division by 0 causing an exception and the program abnormal termination

In order to examine in depth what happens in case the parent process terminates before its child I suggest checking this question and this other one.

Roberto Caboni
  • 7,252
  • 10
  • 25
  • 39