我正在使用分叉的服務器上工作,它在共享內存中存儲一個字符串映射(k-> v)。我想這樣做非常簡單,但是我失去了指針以及我需要複製的東西。所以我提取相關的代碼看起來像這樣:C:將結構與字符串複製到共享內存
struct key_value {
char key[32];
char value[32];
};
struct key_value **map;
int *map_size;
int shmid = shmget(IPC_PRIVATE, sizeof(struct key_value**), 0600);
map = (struct key_value**) shmat(shmid, 0, 0);
int shmid_size = shmget(IPC_PRIVATE, sizeof(int), 0600);
map_size = (int*) shmat(shmid_size, 0, 0);
*map_size = 0;
//the above happens before fork()
char *c = "abc";
int shmid_struct = shmget(IPC_PRIVATE, sizeof(struct key_value*), 0600);
struct key_value *entry = (struct key_value*) shmat(shmid_struct, 0, 0);
*entry->key = *c;
printf("%s\n", map[0]->key);
//smhdt's & shmctl's
所以,我要的是該字符串從*c
複製到map
所以到共享內存中。顯然,我還沒有完全理解指針和結構,因此希望有人能夠清除它。我目前得到一個segfault'主'(謝謝gdb ...)。
請注意,我現在確定具有固定max_size的地圖(雖然動態的話會很棒)。
編輯:在一個答案中指出,在結構中有一個char*
很困難,所以用char [x]來代替。已更新代碼以反映這一點,但仍無法正常工作。
不要那樣做....閱讀更多,特別是[shm_overview(7)](http://man7.org/linux/man-pages/man7/shm_overview.7.html) –
您最新的編輯完全改變了問題。這沒有意義。停下來。 –