2012-02-17 11 views
-1

次のコードを確認することをお勧めします。Linuxで実行しているセグメンテーション違反。共有メモリへの書き込み時のセグメンテーションフォルト

#deinf QID 2012 

typedef struct { 
    pid_t  pid; 
    pthread_t tid; 
    char  msg; 
} MSG; 

typedef struct { 
    int q_head; 
    int q_rear; 
    MSG msgbuf[16*1024]; 
} QUE; 

int attach_que(int que_name, int *shmid, void *shm_ptr) 
{ 

    *shmid = shmget((key_t)que_name, sizeof(QUE), 0666 | IPC_CREAT); 
    if (*shmid == -1) 
    { 
     printf("%d:%d failed to get shared memory.\n", getpid(),que_name); 
     return -1; 
    } 

    printf("%d:is attaching to share memory %d.\n", getpid(), *shmid); 

    shm_ptr = shmat(*shmid, (void *)0, 0); 
    if (shm_ptr == (void *)-1) 
    { 
     printf("%d:%d failed to attch to shmget.\n", getpid(),que_name); 
     return -1; 
    } 

    printf("%d: attched to share memory %d.\n", getpid(),*shmid); 
    return -1; 

} 

int main() 
{ 

    void  *shm_ptr = NULL; 
    TDM_QUE  *tdm_que_ptr; 
    DMINT  shmid; 
    pid_t  pid; 

    pid = getpid(); 

    printf("L-SIMCO %d:is starting.\n", pid); 

    attach_tdm_que(Q_LSIMCO, &shmid, shm_ptr); 
    printf("LSMICO %d:shared memory 0x%x as Q_%d.\n", pid, shm_ptr, Q_LSIMCO); 
    tdm_que_ptr = (TDM_QUE *)shm_ptr; 
    tdm_que_ptr->q_head = 0; 
    tdm_que_ptr->q_rear = 0; 

    /* if this is not first time when creating shared memory, do not init data */ 
    if (tdm_que_ptr->is_creat != 777777) 
    { 
     printf("%d: Init shared memory 0x%x by LSIMCO %d.\n", pid, shm_ptr, Q_LSIMCO); 
     /* init data for shared memory */ 

     tdm_que_ptr->is_creat = 777777; 
    } 

    printf("%d is reading shared memory 0x%x.\n",pid,shm_ptr); 
    ... 
} 
========================= 
Running result is following: 
-bash-3.2$ ./lsimco 
6341:is starting. 
QUE is size of 4620 
6341:is attaching to share memory 0. 
6341: attched to share memory 0. 
6341:shared memory 0x0 as Q_2012. 
Segmentation fault 

感謝。

答えて

1

を有効なポインタを返すために、attach_que呼び出しで使用する必要があります。だから、あなたの呼び出しは私を行う必要があります。

*shm_ptr = shmat(*shmid, (void *)0, 0); 
if (*shm_ptr == (void *)-1) 
{ 
    printf("%d:%d failed to attch to shmget.\n", getpid(),que_name); 
    return -1; 
} 

より多くの事:

attach_tdm_que(Q_LSIMCO, &shmid, &shm_ptr); 

と、もちろん、attach_tdm_queの内側に、適切にポインタasignationを使用あなたはattach_tdm_queからオールウェイズ-1戻ってきています。 さらに、コンパイル可能なコードを投稿します。

+0

ありがとうございます。私の問題はあなたの正しさによって解決されました。 –

+1

@ Joe.Zいいえvote ???? ???? ;-) –

+0

申し訳ありませんが、投票のことは分かりませんでした。今すぐ確認してください。再度、感謝します –

関連する問題