Kackhaufen200

task1_b.c

Apr 26th, 2020
301
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <unistd.h>
  4. #include <sys/types.h>
  5. #include <sys/stat.h>
  6. #include <string.h>
  7. #include <fcntl.h>
  8. #include <sys/ipc.h>
  9. #include <sys/shm.h>
  10. #include <sys/wait.h>
  11. #define SHMSZ 27
  12.  
  13. int main(void)
  14. {
  15.     int shmid;
  16.     key_t key;
  17.     int *shm, *s;
  18.     char path[50];
  19.     int choice[50] = {0};
  20.     int n;
  21.  
  22.     key = 2020;
  23.  
  24.     if ((shmid = shmget(key, SHMSZ, 0666)) < 0) {
  25.         perror("shmget");
  26.         exit(EXIT_FAILURE);
  27.     }
  28.  
  29.     if ((shm = shmat(shmid, NULL, 0)) == (int *) -1) {
  30.         perror("shmat");
  31.         exit(EXIT_FAILURE);
  32.     }
  33.  
  34.     s = shm;
  35.  
  36.     n = *s;
  37.    
  38.     pid_t producer, consumer;
  39.  
  40.     producer = fork();
  41.     consumer = fork();
  42.  
  43.     if(producer == 0 && consumer != 0) {
  44.         int *array;
  45.  
  46.         array = (int *)shmat(shmid, 0, 0);
  47.  
  48.         for(int i = 1; i <= n; i++)
  49.         {
  50.             array[i % 10] = i;
  51.         }
  52.  
  53.         exit(EXIT_SUCCESS);
  54.     }
  55.  
  56.     if(consumer == 0 && producer != 0) {
  57.         int *array;
  58.         int result;
  59.  
  60.         array = shmat(shmid, 0, SHM_RDONLY);
  61.  
  62.         for(int i = 1; i <= n; i++)
  63.         {
  64.             result = result + array[i % 10];
  65.         }
  66.  
  67.         choice[0] = result;
  68.  
  69.         strcpy(path, "/tmp/");
  70.         strcat(path, "task1");
  71.  
  72.         int file = open(path, O_WRONLY);
  73.         write(file, choice, sizeof(choice));
  74.         exit(EXIT_SUCCESS);
  75.     }
  76.  
  77.     if(consumer != 0 && producer != 0) {
  78.         wait(NULL);
  79.     }
  80.  
  81.     return EXIT_SUCCESS;
  82. }
RAW Paste Data