Advertisement
EBobkunov

hotfix 2 ex1

Oct 3rd, 2023 (edited)
22
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.53 KB | Source Code | 0 0
  1. #include <stdio.h>
  2. #include <unistd.h>
  3. #include <sys/types.h>
  4. #include <sys/wait.h>
  5. #include <time.h>
  6.  
  7. void measureExecutionTime(clock_t start_time, const char* process_name) {
  8.     clock_t end_time = clock();
  9.     double execution_time_ms = (double)(end_time - start_time) * 1000 / CLOCKS_PER_SEC;
  10.     printf("%s execution time: %.2f ms\n", process_name, execution_time_ms);
  11. }
  12.  
  13. int main() {
  14.     pid_t pid1, pid2;
  15.     clock_t main_start_time, child1_start_time, child2_start_time;
  16.  
  17.     main_start_time = clock(); // Start measuring main process execution time
  18.  
  19.     printf("Main process: PID=%d, Parent PID=%d\n", getpid(), getppid());
  20.  
  21.     // Create the first child process
  22.     pid1 = fork();
  23.     if (pid1 < 0) {
  24.         perror("Fork failed");
  25.         return 1;
  26.     } else if (pid1 == 0) {
  27.         child1_start_time = clock();
  28.         printf("Child 1: PID=%d, Parent PID=%d\n", getpid(), getppid());
  29.         measureExecutionTime(child1_start_time, "Child 1");
  30.         return 0;
  31.     }
  32.  
  33.     // Create the second child process
  34.     pid2 = fork();
  35.     if (pid2 < 0) {
  36.         perror("Fork failed");
  37.         return 1;
  38.     } else if (pid2 == 0) {
  39.         child2_start_time = clock();
  40.         printf("Child 2: PID=%d, Parent PID=%d\n", getpid(), getppid());
  41.         measureExecutionTime(child2_start_time, "Child 2");
  42.         return 0;
  43.     }
  44.    
  45.     // Wait for both child processes to complete
  46.     waitpid(pid1, NULL, 0);
  47.     waitpid(pid2, NULL, 0);
  48.  
  49.     measureExecutionTime(main_start_time, "Main process");
  50.  
  51.     return 0;
  52. }
  53.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement