共享内存附加问题(分段错误)

问题描述 投票:0回答:1

存在分段错误(*mem_p) = MSG;

如果删除,则打印4并返回。 (shmdt()有问题)

据我所知,shmat()shmget()有问题,但是ipc -m显示分配的内存,所以我想它是shmat()

请我的考试在4个小时内完成,我必须做到这一点...

#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <linux/types.h>
#include <sys/types.h>
#include <linux/ipc.h>
#include <linux/sem.h>
#include <linux/shm.h>
#include <utmp.h>

#define LIM 100
#define MAX_USERS 100
#define PERM 0666
typedef struct mem_msg
{
    int segment;
} Message;

int main(int argc, char *argv[])
{
    Message *mem_p;
    Message MSG;
    struct sembuf mem_close[2] = {0, 0, 0,
                                  0, 1, 0};
    struct sembuf mem_open[1] = {0, -1, 0};
    int semgr, shmid;

    int key = ftok(".", 'c');
    if (key < 0)
    {
        printf("0");
        return;
    }

    semgr = semget(key, 1, PERM | IPC_CREAT);
    if (semgr < 0) {
        printf("1");
        return;
    }
    semctl(semgr, 0, SETVAL, (int)0);

    shmid = shmget(key, sizeof(Message), PERM | IPC_CREAT);
    if (shmid < 0) {
        printf("2");
        return;
    }
    mem_p = shmat(shmid, 0, 0);
    if (mem_p < 0) {
        printf("3");
        return;
    }

    semop(semgr, &mem_close[0], 2);
    MSG.segment = 1;
    (*mem_p) = MSG;
    semop(semgr, &mem_open[0], 1);

    if (shmdt(mem_p) < 0) {
        printf("4");
        return;
    }

    semctl(semgr, 0, IPC_RMID);
    shmctl(shmid, IPC_RMID, 0);

    printf("\nended");
  return 0;
}
c shared-memory
1个回答
-1
投票
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <linux/types.h>
// #include <linux/ipc.h>
// #include <linux/sem.h>
// #include <linux/shm.h>
#include <sys/types.h>
#include <sys/shm.h>
#include <sys/sem.h>
#include <utmp.h>

已帮助(从此开始)

© www.soinside.com 2019 - 2024. All rights reserved.