Advertisement
Guest User

dwadwadwadaw

a guest
Nov 5th, 2017
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.85 KB | None | 0 0
  1. //compile with: gcc -Wall -pthread sharedvariable_posix.c -o svar
  2. //using POSIX named semaphores
  3.  
  4. #include <stdlib.h>
  5. #include <stdio.h>
  6. #include <unistd.h>
  7. #include <errno.h>
  8. #include <sys/types.h>
  9. #include <sys/wait.h>
  10. #include <sys/ipc.h>
  11. #include <sys/sem.h>
  12. #include <fcntl.h>
  13. #include <sys/shm.h>
  14. #include <semaphore.h>
  15.  
  16.  
  17. int * shared_var;
  18. int shmid;
  19. sem_t *mutex;
  20.  
  21. void worker()
  22. {
  23. usleep(1000000 + rand()%11*100000); //uses microseconds sleep and waits 1 to 2 seconds in periods of 0.1 secs
  24. sem_wait(mutex);
  25. (*shared_var)++;
  26. sem_post(mutex);
  27. }
  28.  
  29. int main(int argc, char *argv[])
  30. {
  31. int i, n_procs;
  32.  
  33. if(argc!=2) {
  34. printf("Wrong number of parameters\n");
  35. exit(0);
  36. }
  37.  
  38. n_procs=atoi(argv[1]);
  39.  
  40. // Create shared memory
  41. if( (shmid = shmget(IPC_PRIVATE,sizeof(int),IPC_CREAT|0766)) > 0) {
  42. printf("\nShared memory created\n");
  43. }
  44.  
  45. else {
  46. perror("\nERROR IN CREATING MEMORY\n");
  47. exit(1);
  48. }
  49.  
  50. // Attach shared memory
  51. shared_var = (int *) shmat(shmid,NULL,0);
  52.  
  53. // Create semaphores
  54. sem_unlink("MUTEX");
  55. mutex = sem_open("MUTEX",O_CREAT|O_EXCL,0700,1);
  56.  
  57. // initialize variable in shared memory
  58. (*shared_var) = 1000;
  59.  
  60. // Create worker processes
  61. for(i = 0; i < n_procs; i++) {
  62. if ( fork() == 0 ) {
  63. worker();
  64. exit(0);
  65. }
  66. }
  67. // Wait for all worker processes
  68.  
  69. for(i = 0; i < n_procs; i++) wait(NULL);
  70.  
  71. // print final result
  72. printf("Shared Var: %d\n",(*shared_var));
  73.  
  74. // remove resources (shared memory and semaphores)
  75. sem_close(mutex);
  76. sem_unlink("MUTEX");
  77. shmdt(shared_var);
  78. shmctl(shmid,IPC_RMID,NULL);
  79.  
  80. exit(0);
  81. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement