1 Answers
Parent Terminates Before Child: Scenario-1
#include <unistd.h>
int main() {
int ret;
printf("welcome..pid=%d\n", getpid());
ret = fork();
if (ret < 0) {
perror("fork");
exit(1);
}
if (ret == 0) {
printf("child--welcome,pid=%d,ppid=%d\n", getpid(), getppid());
sleep(2); //Intentional delay in child
printf("wakes up,pid=%d,ppid=%d\n", getpid(), getppid());
exit(0);
} else // ret>0
{
printf("parent--hello,pid=%d,ppid=%d\n", getpid(), getppid());
}
return 0;
}
Parent Terminates Before Child: Scenario-2
#include <unistd.h>
#include <stdio.h>
int main() {
pid_t ret
int i, max = 100;
printf("welcome..pid=%d\n", getpid());
ret = fork();
if (ret < 0) {
perror("fork");
exit(1);
}
if (ret == 0) {
printf("child--welcome,pid=%d,ppid=%d\n", getpid(), getppid());
for (i = 1; i <= max+5; i++) {
printf("wakes up,pid=%d,ppid=%d\n", getpid(), getppid());
sleep(1); //usleep(1000*100)
}
exit(0);
} else // ret>0
{
printf("parent--hello,pid=%d,ppid=%d\n", getpid(), getppid());
for (i = 1; i <= max; i++) {
printf("parent--%d\n", i);
sleep(1);
}
}
return 0;
}
Observations & Understanding
- What is the ppid of child
- After wake up from sleep (Post parent termination) in first examples
- Towards last 4-5 iterations in child’s for loop in second example (max vs max + 5)
- Have you observed that shell prompt came in between, before the completion of child’s output
- Any disadvantages of parent terminates before child process?
- Is it possible to prevent parent termination before the completion of child process?