1

my task is to create zombie process. My code looks like this:

#include <unistd.h>  
#include <stdlib.h>  
#include <stdio.h>  
#include <sys/types.h>  
#include <sys/wait.h>  

int main() {  
    pid_t pid = fork();  

    if (pid == -1) {  
        printf("error\n");  
    }  
    else if (pid == 0) {  
        printf("Child %d\n", getpid());  
        printf("Parents %d\n", getppid());  
        printf("Waiting for my Child to complete\n");  
        exit(0);  
    }  
    else {  
        sleep(5);  
        printf("Parent %d\n",getpid());  
    }  

    return 0;  
}  

When I gcc and execute the file with ./a.out I get the following output:

Child 25097
Parents 25096
Waiting for my child to complete
Parent 25096 ( a few seconds later)

My task is to create a zombie process and print out the exit-state of the child process while being in parent process. Everything is a bit confusing to me because its the first time for me using Linux and C.

Do you have some tips/ hints for me, how to solve the task? Cause I'm not sure if everything is right. I also tried playing with wait(), waitpid() and WEXITSSTATUS(), but I'm not sure about it. And I used the ps x command to check if there is a different output but I didn't notice any changes.

Thanks in advance :)

Chris
  • 26,361
  • 5
  • 21
  • 42
Marco
  • 35
  • 5

1 Answers1

1

This code will successfully create a zombie process.

After the call to fork, the child prints a few lines and exits, while the parent sleeps for 5 seconds. This means you'll have a zombie process for about 5 seconds while the parent is sleeping.

When the sleep is done, the parent prints something and exits. Once the parent exits the child is inherited by the init process, which will wait for the child and make it's pid disappear fro the pid list.

You can also use wait in the parent process, in which case the child is a zombie up until the parent calls wait.

dbush
  • 205,898
  • 23
  • 218
  • 273
  • Is there a way to let child process exit permamently after the sleep of parent has finished? – Marco Oct 23 '21 at 21:07
  • @Marco Not sure what you mean by that. The child has exited “permanently” once it calls `exit`. It then remains a zombie until either it’s parent exits or calls `wait`. – dbush Oct 23 '21 at 21:10
  • OK, got it now. And how do I print out the exit status of the childprocess? while being in parent process? – Marco Oct 23 '21 at 21:13
  • @Marco You get that from `wait`. Check the documentation. – dbush Oct 23 '21 at 21:14
  • Alright, thx :) – Marco Oct 23 '21 at 21:18