fork download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <unistd.h>
  4. #include <sys/wait.h>
  5.  
  6. void task1() {
  7. printf("Task 1 executing...\n");
  8. // Code for task 1 here
  9. }
  10.  
  11. void task2() {
  12. printf("Task 2 executing...\n");
  13. // Code for task 2 here
  14. }
  15.  
  16. void task3() {
  17. printf("Task 3 executing...\n");
  18. // Code for task 3 here
  19. }
  20.  
  21. void create_child(void (*task)()) {
  22. pid_t pid = fork();
  23. if (pid == 0) {
  24. // Child process
  25. task();
  26. exit(0);
  27. } else if (pid > 0) {
  28. // Parent process
  29. return;
  30. } else {
  31. // Fork failed
  32. perror("fork");
  33. exit(1);
  34. }
  35. }
  36.  
  37. int main() {
  38. create_child(task1);
  39. create_child(task2);
  40. create_child(task3);
  41.  
  42. // Parent waits for all child processes to finish
  43. for (int i = 0; i < 3; i++) {
  44. wait(NULL);
  45. }
  46.  
  47. printf("Missions accomplished...\n");
  48. return 0;
  49. }
  50.  
Success #stdin #stdout 0.01s 5284KB
stdin
Standard input is empty
stdout
Task 3 executing...
Task 2 executing...
Task 1 executing...
Missions accomplished...