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

Tạo nhiều tiến trình bằng fork() trong C

Ở đây ta xem dùng fork() tạo tiến trình con trong C. Làm nhiệm vụ khác nhau trong mỗi tiến trình.

fork() trả về giá trị. Nếu > 0: đang ở tiến trình cha (parent). Nếu = 0: đang ở tiến trình con (child). Dùng để phân biệt.

Ví dụ

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

int main() {
    int n = fork(); // chia tiến trình
    if (n > 0) { // parent process
        printf("Parent process \n");
    } else { // child process
        printf("Child process \n");
    }
    return 0;
}

Kết quả

soumyadeep@soumyadeep-VirtualBox:~$ ./a.out
Parent process
soumyadeep@soumyadeep-VirtualBox:~$ Child process
soumyadeep@soumyadeep-VirtualBox:~$