Advertisement
Guest User

Untitled

a guest
Mar 30th, 2017
118
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.00 KB | None | 0 0
  1. #include <sys/ipc.h>
  2. #include <sys/sem.h>
  3. #include <sys/shm.h>
  4. #include <stdio.h>
  5. #include <stdlib.h>
  6. #include "se207_sems.h"
  7.  
  8. /* Remember to try reversing the timings...*/
  9.  
  10.  
  11. int bufferlength = 8; //Limited buffer length
  12. //what could we do about this?
  13.  
  14. int main(int argc, char argv[]){
  15.  
  16. //Create shared memory segment
  17. int shm_id = shmget(ftok("prodcon_example2.c", 2), bufferlength,
  18. 0666 | IPC_CREAT);
  19.  
  20. int shm_id2 = shmget(ftok("prodcon_example2.c", 3), 2,
  21. 0666 | IPC_CREAT);
  22.  
  23. //Use our source file as the "key"
  24. int id = se207_semget("prodcon_example2.c", 0);
  25.  
  26. char* data; //For our pointer to shared memory...
  27. char* location;
  28.  
  29. int pid = fork();
  30. if (pid){
  31. //P1 - CONSUMER
  32. shm_id = shmget(ftok("prodcon_example2.c", 2), 0, 006);
  33. shm_id2 = shmget(ftok("prodcon_example2.c", 3), 0, 006);
  34. //Attach the shared buffer
  35. data = shmat(shm_id, (void *)0, 0);
  36. location = shmat(shm_id2, (void *)0, 0);
  37. while (1){
  38. while (location[0] = location[1]){
  39. }
  40. //printf("Consuming item number %d...\n", location[1]);
  41. printf("consuming");
  42. sleep(1);
  43. //char item = data[location[1]];
  44.  
  45. //printf("Consumed item number %d. Item value was %d\n",
  46. //location[1], item);
  47. //location[1] = (location[1] + 1) % bufferlength;
  48. }
  49. }
  50. else{
  51. //P2
  52. shm_id = shmget(ftok("prodcon_example2.c", 2), 0, 006);
  53. shm_id2 = shmget(ftok("prodcon_example2.c", 3), 0, 006);
  54. //Attach the shared buffer
  55. data = shmat(shm_id, (void *)0, 0);
  56. location = shmat(shm_id2, (void *)0, 0);
  57. while(1){
  58. while ((location[0] + 1) % bufferlength == location[1]){
  59. }
  60. //printf("Producing item number %d...\n", location[0]);
  61. printf("Producing array size %d... value =%d consumer value =%d\n", sizeof(location),location[0], location[1]);
  62. sleep(2);
  63. //data[location[0]] = location[0] * 2; //Simple data, easy to check.
  64. //location[0] = (location[0] + 1) % bufferlength;
  65. //printf("Produced item number %d. Value is %d\n",
  66. //location[0], data[location[0]]);
  67. }
  68. }
  69. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement