我正在尝试将共享内存与我在这里展示的 2 个程序一起使用。a 和 b 是整数数组,array1 和 array2 是字符串数组。这是将数据加载到内存中的第一个代码片段程序
int size = (NUMBER_OF_DATA*(sizeof(int)+sizeof(float)));
key_t key1, key2, key3;
key1 = ftok("/home/an/Desktop/newww.c", 4);
key2 = ftok("/home/an/Desktop/part1.c", 5);
key3 = ftok("/home/an/Desktop/part2.c", 6);
int shmid = shmget(key1, size, 0777|IPC_CREAT);
int shmid1 = shmget(key2, 20*NUMBER_OF_DATA, 0777|IPC_CREAT);
int shmid2 = shmget(key3, 20*NUMBER_OF_DATA, 0777|IPC_CREAT);
int *a = (int *)shmat(shmid, 0, 0);
float *b = (float *)(a + NUMBER_OF_DATA);
char **array1 = (char **)shmat(shmid1, 0, 0);
printf("array1 %p\n", &array1);
char *mempos = (char *)(array1 + NUMBER_OF_DATA);
printf("MEMPOS %p\n", &mempos);
char **array2 = (char **)shmat(shmid2, 0, 0);
char *mempos1 = (char *)(array2 + (NUMBER_OF_DATA));
for(i=0; i<NUMBER_OF_DATA; i++)
{
a[i] = a[i];
b[i] = b[i];
array1[i] = mempos;
strcpy(array1[i], array1[i]);
mempos += 20;
array2[i] = mempos1;
strcpy(array2[i], array2[i]);
mempos1 += 20;
printf("%p %p %p %p\n", &a[i], &b[i], array1[i], array2[i]);
}
j = 0;
while (j<5)
{
j++;
for (i=0; i<NUMBER_OF_DATA; i++)
{
printf("%s %s %d %f\n", array1[i], array2[i], a[i], b[i]);
}
printf("\n");
sleep(2);
}
我正在尝试通过上述文件在共享内存中加载一些数据,并通过下面的文件更改共享内存中的元素。但是,一旦我在下面的文件中更新了一个字符串,我就会从上面的程序中得到垃圾值,而不是改变的值。我完全糊涂了。已尝试使用 gdb 进行调试,但那里一切正常。
int size = (NUMBER_OF_DATA*(sizeof(int)+sizeof(float))) + (2*(20*NUMBER_OF_DATA));
key_t key1, key2, key3;
key1 = ftok("/home/an/Desktop/newww.c", 4);
key2 = ftok("/home/an/Desktop/part1.c", 5);
key3 = ftok("/home/an/Desktop/part2.c", 6);
int shmid = shmget(key1, size, 0777|IPC_CREAT);
int shmid1 = shmget(key2, 20*NUMBER_OF_DATA, 0777|IPC_CREAT);
int shmid2 = shmget(key3, 20*NUMBER_OF_DATA, 0777|IPC_CREAT);
int *a = (int *)shmat(shmid, 0, 0);
float *b = (float *)(a + NUMBER_OF_DATA);
char **array1 = (char **)shmat(shmid1, 0, 0);
printf("array1 %p\n", &array1);
char *mempos = (char *)(array1 + NUMBER_OF_DATA);
printf("MEMPOS %p\n", &mempos);
char **array2 = (char **)shmat(shmid2, 0, 0);
char *mempos1 = (char *)(array2 + (NUMBER_OF_DATA));
int i;
for(i=0; i<5; i++)
{
printf("enter\n");
array1[i] = mempos;
scanf("%s", array1[i]);
mempos += 20;
}
解决办法是什么?