Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <sys/types.h>
- #include <sys/ipc.h>
- #include <sys/shm.h>
- #include <pthread.h>
- #include <string.h>
- #include <stdlib.h>
- // gcc -pthread concat.c -o concat
- // set pshared for interprocess operation
- pthread_mutexattr_t attr;
- int shmid_mutex,shmid_str;
- key_t key;
- // shared memory segment for the mutex
- pthread_mutex_t *shm_mutex;
- // shared memory for the string
- char* shm_str;
- int main(){
- pthread_mutexattr_setpshared(&attr,PTHREAD_PROCESS_SHARED);
- key = 1234;
- // create shm for mutex
- if ((shmid_mutex = shmget(key,sizeof(pthread_mutex_t),IPC_CREAT | 0666)) < 0){
- perror("Could not create shm for mutex");
- exit(1);
- }
- if ((shm_mutex = shmat(shmid_mutex,NULL,0)) < 0){
- perror("Could not attach shm for mutex");
- exit(1);
- }
- // initialize the mutex lock to the shared memory segment
- pthread_mutex_init(shm_mutex,&attr);
- key = 4567;
- // create shared memory segment for storing the string
- if ((shmid_str = shmget(key,sizeof(char)*100,IPC_CREAT | 0666)) < 0){
- perror("Could not create shm for string");
- exit(1);
- }
- if ((shm_str = shmat(shmid_str,NULL,0)) < 0){
- perror("Could not attach shm for string");
- exit(1);
- }
- // initialize the string in shared memory segment
- strcpy(shm_str,"Model Engineering College");
- while(1){
- // lock before modifying the string
- pthread_mutex_lock(shm_mutex);
- printf("%s\n",shm_str);
- strcpy(shm_str,"Model Engineering College");
- // release the lock after modification
- pthread_mutex_unlock(shm_mutex);
- // sleep for 5 secs
- sleep(5);
- }
- return 0;
- }
Add Comment
Please, Sign In to add comment