C 使用shmat时出现段故障

C 使用shmat时出现段故障,c,memory,posix,sharing,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> #

当我到达线路
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

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

shmget(keyForLocalInfo, sizeof(struct localInfo), 
       IPC_CREAT | S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP);
请注意,
shmat
将ptr设置为-1,不为空,因此错误检查没有捕获错误。代码应该是

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

shmat
必须返回NULL。添加对
routerInfo==NULL
的检查,当这种情况发生时,输出
errno
的值以帮助调试问题。不,我使用if-else检查指针routerInfo,它不是NULL。你确定不是你的孩子爆炸了吗?我删除了该部分,问题仍然存在。我用Mac终端运行程序,是不是有问题?我想是你的权限。尝试类似于shmget(keyForLocalInfo、sizeof(struct localInfo)、IPC_create | S|u IRUSR | S|u IRGRP | S|IWGRP)的方法并确保先删除任何现有的shm段。这与segfault发生在
fork()
调用之前的说法不符。孩子从不尝试读或写片段。孩子的
shmctl
调用在最坏的情况下应该返回
EINVAL
-而不是崩溃。@Andrew Medico,“claim”是合适的词。代码没有编译,您和我都不知道孩子在做什么,OP已经排除了他在父进程中附加错误的可能性,
shmctl
在父进程中(除非孩子的
execl
失败),并且我所概述的将在一定时间内发生。虽然我删除了fork进程,但问题仍然存在。我使用Mac终端来运行这些东西,比如“cc-omain.c”。这会是问题吗?好的,那么它是100%在叉子之前。在终端中运行或编译命令都与此无关。我会删除这个答案,也许你可以发布的代码,是不是工作不完全一样,你有吗?
struct localInfo *routerInfo = (struct localInfo*) shmat (shared_localInfo, (void *)0, 0);
if (routerInfo == (void *) -1)
{
    perror("shmat");
    exit(1);
}