C 8
Question 3 part 2 Guest on 6th May 2022 08:02:21 PM
  1. #include <stdio.h>
  2. #include <sys/types.h>
  3. #include <semaphore.h>
  4. #include <sys/stat.h>
  5. #include <fcntl.h>
  6. #include <stdlib.h>
  7. #include <unistd.h>
  8. #include <sys/shm.h>
  9.  
  10. #define BUFF_SIZE 20
  11.  
  12.  
  13. typedef struct {
  14. char buffer[BUFF_SIZE];
  15. int nextIn;
  16. int nextOut;
  17. } shared_data;
  18.  
  19. shared_data *shm, *s;
  20. char sem_name1[] = "mutex";
  21. char sem_name2[] = "empty_slots";
  22. char sem_name3[] = "full_slots";
  23.  
  24. sem_t *empty_slots;
  25. sem_t *full_slots;
  26. sem_t *mutex;
  27.  
  28. void Put(char item)
  29. {
  30.   sem_wait(empty_slots);
  31.   sem_wait(mutex);
  32.   s->buffer[s->nextIn] = item;
  33.   s->nextIn = (s->nextIn + 1) % BUFF_SIZE;
  34.   sem_post(mutex);
  35.   printf("%u is Producing %c ...\n", pthread_self(), item);
  36.   sem_post(full_slots);
  37. }
  38.  
  39. void Producer()
  40. {
  41.     int i;
  42.  
  43.     for(i = 0; i < 20; i++)
  44.     {
  45.       sleep(rand()%3);
  46.       Put((char)('A'+ i % 26));
  47.     }
  48. }
  49.  
  50.  
  51. void main()
  52. {
  53.         mutex=sem_open(sem_name1, O_CREAT,0644, 1);
  54.         full_slots=sem_open(sem_name3, O_CREAT,0644, 0);
  55.         empty_slots=sem_open(sem_name2, O_CREAT,0644, 10);
  56.  
  57.         //allocate the shared memory segment
  58.         key_t key;
  59.         key = 1234;
  60.         //create the segment
  61.         int shmid;
  62.        
  63.         if ((shmid = shmget(key, sizeof(shared_data), IPC_CREAT |0666)) <0)
  64.         {
  65.                 perror("Shmget");
  66.                 exit(1);
  67.         }
  68.         //attach to the segment
  69.         if ((shm = (shared_data *) shmat(shmid, NULL, 0))==(shared_data *) -1)
  70.         {
  71.                 perror("Shmat");
  72.                 exit(1);
  73.         }
  74.        
  75.         s=shm;
  76.         s->nextIn = 0;
  77.  
  78.         Producer( );
  79.         //detach
  80.         shmdt((void *) shm);
  81. }

Paste is for source code and general debugging text.

Login or Register to edit, delete and keep track of your pastes and more.

Raw Paste

Login or Register to edit or fork this paste. It's free.