2016-07-15 2 views
3

나는 공유 메모리에 대해 배우고 내가 그것을 실행할 때리눅스 공유 메모리 세그먼트는 오류

//IPC - Shared Memory 

#include<stdio.h> 
#include<stdlib.h> 
#include<linux/ipc.h> 
#include<linux/msg.h> 
#include<linux/shm.h> 

int main(int argc, char* argv[]) 
{ 
    printf("setting up shared memory\n"); 

    key_t ipc_key; 
    int shmid; 
    int pid; 


    ipc_key = ftok(".",'b'); 

    if((shmid=shmget(ipc_key, 32, IPC_CREAT|0666))==-1) 
    { 
    printf("error creating shared memory\n"); 
    exit(1); 
    } 

    printf("shared memory created with id %d\n",shmid); 

    //fork a child process 
    pid = fork(); 
    printf("fork result %d\n",pid); 
    if(pid==0) 
    { 
    //child process 
    //attach the shared memory 
    int* shm_add_child = (int*)shmat(shmid, 0,0); 
    printf("child attached to shared mem at address %p\n",(void*)shm_add_child); 

    while(1) 
    { 
     printf("%d\n",*shm_add_child); 
     printf("a\n"); 
    } 

    //detach from shm 
    shmdt(shm_add_child); 
    } 
    else 
    { 
    //parent process 
    int* shm_add_parent; 

    shm_add_parent = (int*)shmat(shmid, 0,0); 
    printf("parent attached to shared mem at address %p\n",(void*)shm_add_parent); 
    *shm_add_parent = 10; 

    sleep(10); 

    //detach from shm 
    shmdt(shm_add_parent); 
    } 

    //remove shm 
    shmctl(shmid, IPC_RMID,0); 

    exit(0); 
} 

는 그러나, 나는 세그먼트 오류를 ​​얻을 물건을 테스트하기 위해이 샘플 프로그램을 만들었습니다. 공유 메모리에 대한 내 포인터가 맞지 않는 것 같습니다. 또한 자식 프로세스의 무한 while 루프에서 아무것도 인쇄되지 않습니다.

[email protected]hinkPad-W530:~/Desktop/week1_tasks$ ./ipc_sharedmem_a 
setting up shared memory 
shared memory created with id 5996570 
fork result 8703 
parent attached to shared mem at address 0xffffffff991aa000 
fork result 0 
child attached to shared mem at address 0xffffffff991aa000 
Segmentation fault (core dumped) 

여기에 무슨 문제가 있습니까?

답변

6

왜 마지막 세 헤더 파일을 포함하는지 잘 모르겠습니다. 그것들은 올바른 헤더가 아니며 shm 함수에 대한 잘못된 정의를 줄 것입니다. 심지어 문제가 몇 가지 단서를 제공하는 경고가 생성됩니다 내 시스템 GCC에 대신

test.c:38:26: warning: cast to pointer from integer of different size [-Wint-to-pointer-cast] 
    int* shm_add_child = (int*)shmat(shmid, 0,0); 
         ^
test.c:55:22: warning: cast to pointer from integer of different size [-Wint-to-pointer-cast] 
    shm_add_parent = (int*)shmat(shmid, 0,0); 

을, 당신은 shmat man page에 지정된 단지 사람을 포함해야한다. 구체적으로 :

+0

지적 해 주셔서 감사합니다. 나는 이것 또한 혼란 스러웠다. 하지만 내가 따라 왔던 튜토리얼에는 리눅스 것들이 포함되어있어서 그것들과 함께 갔다. 둘의 차이점은 무엇입니까? – Ankit

+0

그 머리글이 무엇인지 정확히 알지 못합니다. 커널과 라이브러리의 내부에서 사용되는 헤더처럼 보입니다. 언급 된 헤더를 포함하는 – kaylum

+0

은 경고를 제거하지만 세그멘테이션 오류 문제는 계속 발생합니다. – Ankit

관련 문제