我想知道是否有可能在C中获得从shmget创建的共享内存段的大小,而不将段的大小作为数据的一部分?我正在尝试分配一个动态整数数组,并且需要在子进程中找到数组的大小。
主要进程:
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;发布于 2020-02-14 11:13:01
我发现,如果使用shmctl和IPC_STAT标志,就可以获得分配给共享内存段的字节数。然后,您可以将其除以sizeof(int),得到数组的大小。
struct shmid_ds buf;
shmctl(shm, IPC_STAT, &buf);
int length = (int) buf.shm_segsz / sizeof(int);https://stackoverflow.com/questions/60219469
复制相似问题