Create zombie process

前端 未结 2 936
孤城傲影
孤城傲影 2021-01-03 23:46

I am interested in creating a zombie process. To my understanding, zombie process happens when the parent process exits before the children process. However, I tried to recr

2条回答
  •  情歌与酒
    2021-01-04 00:32

    Quoting:

    To my understanding, zombie process happens when the parent process exits before the children process.

    This is wrong. According to man 2 wait (see NOTES) :

    A child that terminates, but has not been waited for becomes a "zombie".

    So, if you want to create a zombie process, after the fork(2), the child-process should exit(), and the parent-process should sleep() before exiting, giving you time to observe the output of ps(1).

    For instance, you can use the code below instead of yours, and use ps(1) while sleep()ing:

    #include 
    #include 
    #include 
    #include 
    #include 
    
    int main(void)
    {
        pid_t pid;
        int status;
    
        if ((pid = fork()) < 0) {
            perror("fork");
            exit(1);
        }
    
        /* Child */
        if (pid == 0)
            exit(0);
    
        /* Parent
         * Gives you time to observe the zombie using ps(1) ... */
        sleep(100);
    
        /* ... and after that, parent wait(2)s its child's
         * exit status, and prints a relevant message. */
        pid = wait(&status);
        if (WIFEXITED(status))
            fprintf(stderr, "\n\t[%d]\tProcess %d exited with status %d.\n",
                    (int) getpid(), pid, WEXITSTATUS(status));
    
        return 0;
    }
    

提交回复
热议问题