Assume in 1.txt file ,i have saved 32
writer.c
-----------
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <stdio.h>
#include<stdlib.h>
#include<fcntl.h>
int main(){
int shm_id;
key_t mem_key;
int *shm_ptr;
int fd=open("1.txt",O_CREAT|O_RDWR,0777);
mem_key = ftok("file.txt", '6');printf("Key=%d\n",mem_key);
shm_id = shmget(mem_key, 4*sizeof(int), IPC_CREAT | 0666);
printf("shm_id=%d\n",shm_id);
if (shm_id < 0) {
printf("*** shmget error (server) ***\n");
exit(1);
}
shm_ptr = (int *) shmat(shm_id, NULL, 0); /* attach */
printf("Printing value in the shared memory%x--&shm_ptr=%p\n",shm_ptr,&shm_ptr);
if (shm_ptr == (int *)-1) {
printf("*** shmat error (server) ***\n");
exit(1);
}
read(fd,&shm_ptr,sizeof(shm_ptr));
write(1,&shm_ptr,sizeof(shm_ptr));------------(1)>here its printing the correct value 32
return 0;
}
reader.c
---------
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <stdio.h>
#include<stdlib.h>
#include<fcntl.h>
int main(){
int shm_id;
key_t mem_key;
int *shm_ptr;
mem_key = ftok("file.txt", '6');printf("Key=%d\n",mem_key);
shm_id = shmget(mem_key, 4*sizeof(int), IPC_CREAT | 0666);
printf("shm_id=%d\n",shm_id);
if (shm_id < 0) {
printf("*** shmget error (server) ***\n");
exit(1);
}
shm_ptr = (int *) shmat(shm_id, NULL, 0); /* attach */
printf("Attached to %x\n",shm_ptr);
if (shm_ptr == (int *)-1) {
printf("*** shmat error (server) ***\n");
exit(1);
}
printf("Printing value in the shared memory :%x &shm_ptr=%p\n",shm_ptr,&shm_ptr);
write(1,&shm_ptr,sizeof(shm_ptr));------>(2)//Here its printing some junk value
return 0;
}
Can any body pls tell me why am i not able to retrieve the correct value in reader.c?shmid & key values are same in both the programs.Where i went wrong?Any help is very appreciable?