简体   繁体   English

深度复制结构到POSIX共享内存

[英]Deep copy structures to POSIX shared memory

I have two structures : 我有两个结构:

struct bets{
   int bets[36];
   int last_bet;
}bets
struct board{
   int type;
   bets *bet;
 }board

I created a chunk of shad memory of sizeof(board) . 我创建了一块sizeof(board)的shad内存。 So, I got a pointer to the Board in shared memory (lest call it ptr). 因此,我在共享内存中找到了指向董事会的指针(至少称为ptr)。 I did created a new board and bets structure, board *b , bets * bts , .... added board->bet = bts . 我并创建了一个新的boardbets结构, board *bbets * bts ,....加入board->bet = bts Now, I copied the "b" to ptr memcpy(ptr, bts, sizeof(board)) . 现在,我将“ b”复制到ptr memcpy(ptr, bts, sizeof(board)) I can access the ptr->type . 我可以访问ptr->type But when I try to access ptr->bet->last_bet , I get a segmentation-fault error. 但是,当我尝试访问ptr->bet->last_bet ,出现了细分错误错误。

I also tried copying like this: 我也尝试这样复制:

board *b;
memcpy(ptr, b, sizeof(board));
bets *bts;
memcpy(ptr->bet, bts, sizeof(bets)).

Still getting segmentation-fault error. 仍然出现分段错误错误。

How can I copy both struct one inside of the other and still have access to the nested one? 如何将两个struct都复制到另一个中,并且仍然可以访问嵌套的一个?

Standard "deep copying" into shared memory is not useful because the pointers, even if they point into the shared memory segment, are local to your process's virtual address space and won't be the same when another process maps the shared memory. 将标准“深度复制”到共享内存中没有用,因为即使它们指向共享内存段,指针也位于进程的虚拟地址空间本地,并且在另一个进程映射共享内存时它们不会相同。 Instead of pointers, you need to store offsets from the beginning of the shared memory segment. 您需要存储从共享内存段的开头开始的偏移量,而不是指针。 size_t would be an appropriate type. size_t将是适当的类型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM