Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Lập Trình C

Thực thi zombie process và orphan process trong một chương trình C

Ở đây ta xem cách thực thi zombie process và orphan process trong một chương trình C/C++. Trước khi vào chính, xem khái niệm.

Zombie Process (Tiến trình zombie)

Tiến trình đã hoàn thành thực thi nhưng vẫn có entry trong process table. Thường xảy ra với child process, vì parent process vẫn cần đọc exit status của con. Khi dùng system call wait, zombie process bị loại khỏi process table. Gọi là "reaping the zombie process".

Orphan Process (Tiến trình mồ côi)

Tiến trình vẫn chạy dù parent process đã kết thúc. Có thể orphan cố ý hoặc không cố ý.

  • Cố ý: Chạy background không cần hỗ trợ thủ công. Dùng cho service chạy vô hạn hoặc job dài không cần user chú ý.
  • Không cố ý: Parent crash hoặc terminate. Tránh được bằng process group mechanism.

Trong code sau, ta thực thi zombie và orphan cùng lúc. Parent có child, child có grandchild. Nếu control vào child, sleep 5s để parent kết thúc → child thành orphan. Sau đó grandchild thành zombie khi parent (child của main) sleep 1s. Grandchild kết thúc mà parent không gọi terminate, entry vẫn còn trong process table.

Ví dụ

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

int main() {
    int x = fork(); // tạo child process
    if (x > 0) // parent process
        printf("Inside Parent---- PID is : %d\n", getpid());
    else if (x == 0) { // child process
        sleep(5); // chờ parent kết thúc
        x = fork();
        if (x > 0) {
            printf("Inside Child---- PID :%d and PID of parent : %d\n", getpid(), getppid());
            while (1)
                sleep(1);
            printf("Inside Child---- PID of parent : %d\n", getppid());
        } else if (x == 0)
            printf("Inside grandchild process---- PID of parent : %d\n", getppid());
    }
    return 0;
}

Kết quả

soumyadeep@soumyadeep-VirtualBox:~$ ./a.out
Inside Parent---- PID is : 3821
soumyadeep@soumyadeep-VirtualBox:~$ Inside Child---- PID :3822 and PID of parent : 686
Inside grandchild process---- PID of parent : 3822
soumyadeep@soumyadeep-VirtualBox:~$