Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> การเขียนโปรแกรม C

รัน Zombie และ Orphan Process ในโปรแกรม C เดียว

Zombie Process: Process จบแล้วแต่ยังอยู่ใน Process Table (รอ Parent อ่าน Exit Status)

Orphan Process: Process ยังทำงานอยู่แต่ Parent จบไปแล้ว (ถูก Adopt โดย init)

ตัวอย่างรันพร้อมกัน

#include <stdio.h>
#include <unistd.h>

int main() {
    int x = fork(); // Child
    if (x > 0) {
        printf("Parent PID: %d\n", getpid());
    } else {
        sleep(5); // รอ Parent จบ -> กลายเป็น Orphan
        x = fork(); // Grandchild
        if (x > 0) {
            printf("Child PID: %d, Parent PID: %d\n", getpid(), getppid());
            while(1) sleep(1); // รอ Grandchild จบ -> Grandchild กลายเป็น Zombie
        } else {
            printf("Grandchild PID: %d, Parent PID: %d\n", getpid(), getppid());
            // Grandchild จบทันที -> Zombie
        }
    }
    return 0;
}

ผลลัพธ์

Parent PID: 3821
Child PID: 3822, Parent PID: 686 (init)
Grandchild PID: 3823, Parent PID: 3822