shared memory 에 저장된 data 를 읽어오고 싶습니다.
글쓴이: srdpt3 / 작성시간: 목, 2011/07/07 - 2:25오전
어느 configuration 의 파일에 setting 된 user key와 user size 값으로
공유메모리에 접근하여 그안에 저장된 값을 읽어 오고 싶은데요 이게 가능한가요?
#include<stdio.h> #include<stdlib.h> #include<sys/types.h> #include<sys/ipc.h> #include<sys/shm.h> #include<string.h> #include<sys/stat.h> #define MAX_BUF 256 #define MAX 30 int shared(int argc ,char *argv[]) { FILE *in ; char s[MAX]; char *ptr; char *ptr_p; char *ptr_size; char *ptr_p2; struct shmid_ds shmid_buffer; long size; int key,shmid, len,rtrn; char *shared_memory,*sh; char *sh_array; char *c1 = "USR_SHMKEY="; char *c2 = "USR_SHMSIZE="; char* shared_stuff; char filename[40]=""; char *string; int segment_size; char buf[MAX_BUF]; strcat(filename,argv[2]); strcat(filename,".conf"); if((chdir("/config"))==-1) { fputs("cannnot move to this directory\n",stderr); exit(1); } if((in=fopen(filename,"r")) == NULL) { fputs("cannot open input file \n",stderr); exit(1); } while(fgets(s,MAX,in)!=NULL) { ptr=strstr(s,c1); ptr_size=strstr(s,c2); if(ptr) { ptr_p=strtok(ptr,""); key = atoi(ptr_p+11); printf("key is : %d\n",key); } if(ptr_size) { ptr_p2=strtok(ptr_size,""); size = atol(ptr_p2+12); printf("SIZE is : %d\n",size); } } //fcloseall(); //if ((shmid = shmget((key_t)key,(size_t)size,IPC_CREAT|0666)) == -1) if ((shmid = shmget((key_t)key,(size_t)size,S_IRUSR|S_IWUSR)) == -1) { perror("shmget failed"); exit(1); } shared_memory=(char *)shmat(shmid, NULL,SHM_RDONLY); if(shared_memory ==(char *)-1){ perror("shmat failed"); exit(1); } printf("Memory is atatched at %X\n",(int)shared_memory); memcpy(buf,shared_memory,sizeof(&shared_memory)); printf("Received from shared memory is %s\n",(char*)shared_memory); printf("Received from shared memory is %s\n",buf); shmctl(shmid,IPC_STAT,&shmid_buffer); segment_size = shmid_buffer.shm_segsz; printf("segment size : %d\n",segment_size); shmdt(shared_memory); return 0; }
결과 화면
key is : 70500
SIZE is : 67108864
Memory is atatched at B36E5000
Received from shared memory is
Received from shared memory is
일단 그 conf 파일안에 있는 USR_SHMKEY 값과 USR_SHMSIZE 를 읽어드려서 그값들로 공유메모리에 접근하는건데요
잘하고 있는지 몰라서 물어봅니다.
보시다시피 Received from shared memory is 이후 아무 값도 아찍히는데요
제가 잘못 이해하고 있는지 물어보고싶습니다
고수님들 좀 도와주세요ㅣ.
Forums:
댓글 달기