Guest User

Untitled

a guest
Apr 19th, 2018
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.52 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <sys/types.h>
  3. #include <sys/ipc.h>
  4. #include <sys/shm.h>
  5. #include <pthread.h>
  6. #include <string.h>
  7. #include <stdlib.h>
  8.  
  9. // gcc -pthread concat.c -o concat
  10.  
  11.  
  12. // set pshared for interprocess operation
  13. pthread_mutexattr_t attr;
  14.  
  15.  
  16.  
  17. int shmid_mutex,shmid_str;
  18. key_t key;
  19.  
  20. // shared memory segment for the mutex
  21. pthread_mutex_t *shm_mutex;
  22.  
  23. // shared memory for the string
  24. char* shm_str;
  25.  
  26. int main(){
  27.  
  28. pthread_mutexattr_setpshared(&attr,PTHREAD_PROCESS_SHARED);
  29. key = 1234;
  30.  
  31. // create shm for mutex
  32. if ((shmid_mutex = shmget(key,sizeof(pthread_mutex_t),IPC_CREAT | 0666)) < 0){
  33. perror("Could not create shm for mutex");
  34. exit(1);
  35. }
  36.  
  37. if ((shm_mutex = shmat(shmid_mutex,NULL,0)) < 0){
  38. perror("Could not attach shm for mutex");
  39. exit(1);
  40. }
  41.  
  42. // initialize the mutex lock to the shared memory segment
  43. pthread_mutex_init(shm_mutex,&attr);
  44.  
  45. key = 4567;
  46.  
  47.  
  48. // create shared memory segment for storing the string
  49. if ((shmid_str = shmget(key,sizeof(char)*100,IPC_CREAT | 0666)) < 0){
  50. perror("Could not create shm for string");
  51. exit(1);
  52. }
  53.  
  54. if ((shm_str = shmat(shmid_str,NULL,0)) < 0){
  55. perror("Could not attach shm for string");
  56. exit(1);
  57. }
  58.  
  59. // initialize the string in shared memory segment
  60. strcpy(shm_str,"Model Engineering College");
  61.  
  62.  
  63. while(1){
  64. // lock before modifying the string
  65. pthread_mutex_lock(shm_mutex);
  66. printf("%s\n",shm_str);
  67. strcpy(shm_str,"Model Engineering College");
  68. // release the lock after modification
  69. pthread_mutex_unlock(shm_mutex);
  70.  
  71. // sleep for 5 secs
  72. sleep(5);
  73. }
  74.  
  75. return 0;
  76. }
Add Comment
Please, Sign In to add comment