fork download
  1. #include <stdio.h>
  2. #include <unistd.h>
  3. #include <sys/wait.h> // สำหรับใช้ฟังก์ชัน wait()
  4.  
  5. int main() {
  6. pid_t pid;
  7.  
  8. // สร้างกระบวนการย่อยตัวที่ 1
  9. pid = fork();
  10. if (pid < 0) {
  11. // ถ้าการ fork ล้มเหลว
  12. fprintf(stderr, "Fork failed\n");
  13. return 1;
  14. } else if (pid == 0) {
  15. // นี่คือโค้ดที่กระบวนการย่อยตัวที่ 1 จะทำงาน
  16. printf("Child 1: Process ID - %d, Parent ID - %d\n", getpid(), getppid());
  17. printf("Child 1: Finished work.\n");
  18. return 0;
  19. }
  20.  
  21. // สร้างกระบวนการย่อยตัวที่ 2
  22. pid = fork();
  23. if (pid < 0) {
  24. // ถ้าการ fork ล้มเหลว
  25. fprintf(stderr, "Fork failed\n");
  26. return 1;
  27. } else if (pid == 0) {
  28. // นี่คือโค้ดที่กระบวนการย่อยตัวที่ 2 จะทำงาน
  29. printf("Child 2: Process ID - %d, Parent ID - %d\n", getpid(), getppid());
  30. printf("Child 2: Finished work.\n");
  31. return 0;
  32. }
  33.  
  34. // โค้ดนี้จะทำงานในกระบวนการหลักเท่านั้น
  35. printf("Parent: Process ID - %d\n", getpid());
  36. printf("Parent: Doing some work...\n");
  37.  
  38. // รอให้กระบวนการย่อยทั้งสองสิ้นสุดการทำงาน
  39. wait(NULL); // รอ child process ตัวแรก
  40. wait(NULL); // รอ child process ตัวที่สอง
  41.  
  42. printf("Parent: All child processes have finished. Now parent finishes.\n");
  43. return 0;
  44. }
  45.  
Success #stdin #stdout 0.01s 5292KB
stdin
Standard input is empty
stdout
Child 2: Process ID - 564169, Parent ID - 564154
Child 2: Finished work.
Child 1: Process ID - 564168, Parent ID - 564154
Child 1: Finished work.
Parent: Process ID - 564154
Parent: Doing some work...
Parent: All child processes have finished. Now parent finishes.