当我使用shmat时出现段故障

时间:2014-04-16 17:07:48

标签: c memory posix sharing

当我到达routerInfo->areaID行时,我遇到了段错误:那部分是11。 好像我没有成功分配内存。 我只是不知道为什么。 任何人都可以解决这个问题吗?

我的标题是这样的:

#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/shm.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdlib.h>
#include<memory.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/ipc.h>
#include <semaphore.h>
#include <time.h>
#include <signal.h>
#include <fcntl.h>
#include <stdbool.h>
#include <netdb.h>
#include <sys/time.h>
#include <sys/ioctl.h>


#define QUEUE_SIZE 300
#define MAX_CONN 10
#define TYPE_ROUTE 1
#define TYPE_TERMINAL 2
#define CONN_INIT false
#define CONN_ESTB true
#define CSPORT 39246



struct localInfo{
    char router_ID[16];

    int helloTime;
    int protocol_Version;
    int update_Interval;
    int area_ID;
    int neighborNum;
};
//shared information struct

和我的主要功能是:

#include "BasicHeader.h"


int shared_hello, shared_lsa, shared_ping, shared_data, shared_localInfo;//using shared memory
pid_t childpid;//using for child process

int main(){
    printf("Starting router ... ");
    sleep(1);

    key_t keyForLocalInfo = ftok(".", 1);


    shared_localInfo = shmget ( keyForLocalInfo , sizeof(struct localInfo) , IPC_CREAT) ;
    if (shared_localInfo == -1) {perror("error creating");exit(1);}
    printf("shared_localInfo: %d\n", shared_localInfo);
    //creating the queue for shared_localInfo


    system("ipcs -m");
    //show the shm status
    //creating the sharing memory finished

    struct localInfo *routerInfo = (struct localInfo*) shmat (shared_localInfo, (void *)0, 0);
    if (routerInfo == NULL) {
        perror("shmat");exit(1);
    }

    routerInfo->area_ID = 0;
    routerInfo->helloTime = 45;
    routerInfo->neighborNum = 0;
    routerInfo->protocol_Version = 1;
    routerInfo->update_Interval = 180;
    shmdt(routerInfo);

    int err = 0;
    if  ((err = shmctl(shared_localInfo, IPC_RMID, 0) == -1))
        perror("shmctl shared_localInfo");


}

1 个答案:

答案 0 :(得分:0)

更改semget上的权限以允许访问,例如

shmget(keyForLocalInfo, sizeof(struct localInfo), 
       IPC_CREAT | S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP);

请注意shmat将ptr设置为-1,而不是NULL,因此错误检查没有捕获错误。代码应该是

struct localInfo *routerInfo = (struct localInfo*) shmat (shared_localInfo, (void *)0, 0);
if (routerInfo == (void *) -1)
{
    perror("shmat");
    exit(1);
}