fork download
  1. #include <stdio.h>
  2. #include <unistd.h>
  3. #include <sys/wait.h>
  4. #include <stdlib.h>
  5. #include <stdbool.h>
  6.  
  7. bool is_prime(int num) {
  8. if (num <= 1) return false;
  9. for (int i = 2; i <= num / 2; i++) {
  10. if (num % i == 0) return false;
  11. }
  12. return true;
  13. }
  14.  
  15. int main() {
  16. pid_t pid1, pid2, parent_pid;
  17.  
  18. parent_pid = getpid();
  19.  
  20. pid1 = fork();
  21.  
  22. if (pid1 == 0) {
  23. // Child Process 1
  24. int child1_pid = getpid();
  25. if (is_prime(child1_pid)) {
  26. printf("Child 1 (PID %d): My PID is a prime number.\n", child1_pid);
  27. } else {
  28. printf("Child 1 (PID %d): My PID is not a prime number.\n", child1_pid);
  29. }
  30. exit(0);
  31. } else {
  32. pid2 = fork();
  33.  
  34. if (pid2 == 0) {
  35. // Child Process 2
  36. if (is_prime(parent_pid)) {
  37. printf("Child 2 (PID %d): My parent's PID (%d) is a prime number.\n", getpid(), parent_pid);
  38. } else {
  39. printf("Child 2 (PID %d): My parent's PID (%d) is not a prime number.\n", getpid(), parent_pid);
  40. }
  41. exit(0);
  42. } else {
  43. // Parent Process
  44. wait(NULL);
  45. wait(NULL);
  46. printf("Parent (PID %d): Missions accomplished...\n", parent_pid);
  47. }
  48. }
  49. return 0;
  50. }
  51.  
Success #stdin #stdout 0s 5280KB
stdin
Standard input is empty
stdout
Child 2 (PID 1009175): My parent's PID (1009171) is not a prime number.
Child 1 (PID 1009174): My PID is not a prime number.
Parent (PID 1009171): Missions accomplished...