简体   繁体   中英

Creating Zombie process in C (Linux)

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 :)

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM