Question

When I reach the line routerInfo->areaID, I got segment fault: 11 on that part. It seem that I do not allocate the memory successfully. I just do not know why. Can any one solve this problem?

My header is like this:

#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

and My main function is:

#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");


}
Was it helpful?

Solution

Change the permissions on semget to allow access e.g.

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

Note that shmat returns a ptr set to -1, not NULL, and thus the error check was not catching the error. The code should have been

struct localInfo *routerInfo = (struct localInfo*) shmat (shared_localInfo, (void *)0, 0);
if (routerInfo == (void *) -1)
{
    perror("shmat");
    exit(1);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top