Hi gurus can you explain following lines of code ?
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
int main(void)
{
pid_t pid;
int rv;
switch(pid = fork()) {
case -1:
perror("fork"); /* something went wrong */
exit(1); /* parent exits */
case 0:
printf(" CHILD: This is the child process!\n");
printf(" CHILD: My PID is %d\n", getpid());
printf(" CHILD: My parent's PID is %d\n", getppid());
printf(" CHILD: I am sleeping for 15 seconds\n");
sleep(15); // exits as a second
printf(" CHILD: Sleeping is over\n");
default:
printf("PARENT: This is the parent process!\n");
printf("PARENT: My PID is %d\n", getpid());
printf("PARENT: My child's PID is %d\n", pid);
printf("PARENT: I am sleeping for 10 seconds\n");
sleep(10); // exits first
printf("PARENT: Sleeping is over\n");
}
return 0;
}
As far as I know:
- if fork() function is called - code is executing in child and parent section (if fork() did not exits with -1 of course)
- after calling fork() function all code after fork() is executed sequentially (but due to sheduller is unable to predict if will be executed parent or child part of code)
- if parent code exits before child code (without waiting or hadnling signal), childs new parent will be init proces (PPID 1)
I get the following output
bash-3.2$ ./a2.out
PARENT: This is the parent process!
CHILD: This is the child process!
PARENT: My PID is 15852
PARENT: My child's PID is 15853
PARENT: I am sleeping for 10 seconds
CHILD: My PID is 15853
CHILD: My parent's PID is 15852
CHILD: I am sleeping for 15 seconds
PARENT: Sleeping is over
bash-3.2$ CHILD: Sleeping is over
PARENT: This is the parent process!
PARENT: My PID is 15853
PARENT: My child's PID is 0
PARENT: I am sleeping for 10 seconds
PARENT: Sleeping is over
So my question is:
- why is not child mark as defunct when parent exits first ? (I tried ps -elf | grep defunct during execution of code)
- Why is parent code executed second time (but now with the pid of child ?)
Thanks a lot