gpt4 book ai didi

c - 当我使用 shmat 时出现段错误

转载 作者:行者123 更新时间:2023-11-30 17:35:05 26 4
gpt4 key购买 nike

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

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com