Advertisement
EBobkunov

ex2 w6 worker.c

Oct 16th, 2023
55
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 2.24 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <unistd.h>
  4. #include <signal.h>
  5. #include <time.h>
  6. #include <stdbool.h>
  7.  
  8. // 6 digits for big triangular numbers like 113050
  9. #define TRI_BASE 1000000
  10.  
  11. // Current process pid (which executed this program)
  12. pid_t pid;
  13.  
  14. // Current process idx (starts from 0)
  15. int process_idx;
  16.  
  17. // Number of triangular numbers found so far
  18. long tris;
  19.  
  20. bool is_triangular(long n) {
  21.     for (long i = 1; i <= n; i++) {
  22.         if (i * (i + 1) == 2 * n) {
  23.             return true;
  24.         }
  25.     }
  26.     return false;
  27. }
  28.  
  29. void signal_handler(int signum) {
  30.     switch (signum) {
  31.         case SIGTSTP:
  32.             // Pause the process indefinitely
  33.             printf("Process %d: stopping....\n", process_idx);
  34.             pause();
  35.             break;
  36.         case SIGCONT:
  37.             // Continue the process
  38.             printf("Process %d: resuming....\n", process_idx);
  39.             break;
  40.         case SIGTERM:
  41.             // Terminate the process
  42.             printf("Process %d: terminating....\n", process_idx);
  43.             exit(EXIT_SUCCESS);
  44.             break;
  45.         default:
  46.             break;
  47.     }
  48. }
  49.  
  50. // Generates a big number n
  51. long big_n() {
  52.     time_t t;
  53.     long n = 0;
  54.     srand((unsigned)time(&t));
  55.     while (n < TRI_BASE)
  56.         n += rand();
  57.     return n % TRI_BASE;
  58. }
  59.  
  60. int main(int argc, char *argv[]) {
  61.     if (argc != 2) {
  62.         fprintf(stderr, "Usage: %s <process_idx>\n", argv[0]);
  63.         exit(EXIT_FAILURE);
  64.     }
  65.  
  66.     process_idx = atoi(argv[1]); // Get process_idx from command line argument
  67.     pid = getpid();
  68.  
  69.     // Register signal handlers
  70.     signal(SIGTSTP, signal_handler);
  71.     signal(SIGCONT, signal_handler);
  72.     signal(SIGTERM, signal_handler);
  73.  
  74.     long next_n = big_n() + 1;
  75.  
  76.     printf("Process %d (PID=%d): has been started\n", process_idx, pid);
  77.     printf("Process %d (PID=%d): will find the next triangular number from [%ld, inf)\n", process_idx, pid, next_n);
  78.  
  79.     // Initialize counter
  80.     tris = 0;
  81.  
  82.     while (true) {
  83.         if (is_triangular(next_n)) {
  84.             tris++;
  85.             printf("Process %d (PID=%d): I found this triangular number %ld\n", process_idx, pid, next_n);
  86.         }
  87.         next_n++;
  88.     }
  89.  
  90.     return 0;
  91. }
  92.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement