在 C shmget 中查找共享内存的大小

Find size of shared memory in C shmget

我想知道是否可以在不将段大小作为数据一部分的情况下获取从 shmget 创建的 C 中共享内存段的大小?我正在尝试分配一个动态 int 数组,并且需要在子进程中找到该数组的大小。

主要流程:

int sizeOfArray = 3;
int shm = shmget(IPC_PRIVATE, sizeof(int) * sizeOfArray, IPC_CREAT | 0666);
int *a = (int*) shmat(shm, NULL, 0);
a[0] = 0;
a[1] = 1;
a[2] = 2;
if (fork() == 0) {
    char *args[3];
    char shmID[11];
    bzero(shmID, 11);
    intToString(shm, shmID); // custom function that does what the name implies
    args[0] = "slave";
    args[1] = shmID;
    args[2] = NULL;
    execvp("slave", args);
    return -1;
}

wait(NULL);
shmdt((void*) a);
shmctl(shm, IPC_RMID, NULL);

子进程(从):

int shm = atoi(argv[1]);
int *ptr = (int*) shmat(shm, NULL, 0);
//TODO: find length of int array in shared memory
shmdt((void*) ptr);
return 0;

我发现如果你使用shmctlIPC_STAT标志,你可以获得分配给共享内存段的字节数。然后你可以将它除以 sizeof(int) 得到你的数组的大小。

struct shmid_ds buf;
shmctl(shm, IPC_STAT, &buf);
int length = (int) buf.shm_segsz / sizeof(int);