当我到达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");


}

最佳答案

更改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);
}

关于c - 使用shmat时出现段故障,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/23115861/

10-09 15:41