Advertisement
Guest User

Untitled

a guest
Oct 21st, 2017
54
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.03 KB | None | 0 0
  1. /**
  2. * Simple program demonstrating shared memory in POSIX systems.
  3. *
  4. * This is the producer process that writes to the shared memory region.
  5. *
  6. * Figure 3.17
  7. *
  8. * @author Silberschatz, Galvin, and Gagne
  9. * Operating System Concepts - Ninth Edition
  10. * Copyright John Wiley & Sons - 2013
  11. */
  12.  
  13.  
  14. #include <stdio.h>
  15. #include <stdlib.h>
  16. #include <string.h>
  17. #include <fcntl.h>
  18. #include <sys/shm.h>
  19. #include <sys/stat.h>
  20. #include <sys/mman.h>
  21.  
  22. int main(int argc, char **argv)
  23. {
  24. const int SIZE = 4096;
  25. const char *name = "OS";
  26. const char *message0= "Studying ";
  27. const char *message1= "Operating Systems ";
  28. const char *message2= "Is Fun!";
  29. int BUFFER_SIZE = 0;
  30. int NUM_PRODUCERS = 0;
  31. int NUM_MESSAGES = 0;
  32.  
  33. int shm_fd;
  34. void *ptr;
  35.  
  36. checkArgs(argc,argv);
  37. /* create the shared memory segment */
  38. shm_fd = shm_open(name, O_CREAT | O_RDWR, 0666);
  39.  
  40. /* configure the size of the shared memory segment */
  41. ftruncate(shm_fd,SIZE);
  42.  
  43. /* now map the shared memory segment in the address space of the process */
  44. ptr = mmap(0,SIZE, PROT_READ | PROT_WRITE, MAP_SHARED, shm_fd, 0);
  45. if (ptr == MAP_FAILED) {
  46. printf("Map failed\n");
  47. return -1;
  48. }
  49.  
  50. /**
  51. * Now write to the shared memory region.
  52. *
  53. * Note we must increment the value of ptr after each write.
  54. */
  55. sprintf(ptr,"%s",message0);
  56. ptr += strlen(message0);
  57. sprintf(ptr,"%s",message1);
  58. ptr += strlen(message1);
  59. sprintf(ptr,"%s",message2);
  60. ptr += strlen(message2);
  61.  
  62. return 0;
  63. }
  64.  
  65. void produce()
  66. {
  67.  
  68. }
  69.  
  70. void checkArgs(int argc, char **argv)
  71. {
  72. if(argc == 1){
  73. BUFFER_SIZE = 10;
  74. NUM_PRODUCERS = 5;
  75. NUM_MESSAGES = 100;
  76. }
  77.  
  78. if(argc == 2 && (argv[0] == "-h")){
  79. displayHelp();
  80. }
  81.  
  82. if(argc == 4 && (numCheck(argv[0])) && (numCheck(argv[1))
  83. && (numCheck(argv[2]))){
  84. BUFFER_SIZE = argv[0];
  85. NUM_PRODUCERS = argv[1];
  86. NUM_MESSAGES = argv[2];
  87. }
  88.  
  89. else {
  90. displayHelp();
  91. }
  92. }
  93.  
  94. void displayHelp()
  95. {
  96. printf("help");
  97. }
  98.  
  99. int numCheck(int x)
  100. {
  101. if((x >= 1) && (x <= 100)){
  102. return x;
  103. } else
  104. return 0;
  105.  
  106. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement