如何修改共享内存(shmget的/的shmat)用C? [英] How to modify shared memory (shmget/shmat) in C?
问题描述
我有一个结构:
struct sdata {
int x;
int y;
time_t time;
};
我创建的结构共享内存如下:
I create shared memory for the struct as follows:
size_t shmsize = sizeof(struct sdata);
shmid = shmget(IPC_PRIVATE, shmsize, IPC_CREAT | 0666);
然后我访问共享内存是这样的:
Then I access the shared memory like this:
struct sdata *data = shmat(shared.shmid, (void *) 0, 0);
data->time = time(NULL); // function returns the current time
我的问题是pretty简单。这是访问/修改共享内存的正确方法?这是最好的办法?
My question is pretty simple. Is this the right way to access/modify shared memory? Is this the best approach?
(我使用的同步System V信号,我还没有列入该code,我只是想确认我访问/修改正确的共享内存)。
(I am using System V semaphores for synchronization and I haven't included that code. I just wanted to make sure I am accessing/modifying the shared memory correctly.)
推荐答案
这是正确的,需要注意的唯一的事情就是你正在创建一个私人共享内存段,这意味着你必须以某种方式传输的shmid任何你希望其他进程具有使用它。
This is correct, the only thing of note is that you are creating a PRIVATE shared memory segment, which means you'll have to transmit the shmid somehow to any other process that you want to have use it.
这篇关于如何修改共享内存(shmget的/的shmat)用C?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!