How to modify shared memory (shmget/shmat) in C?

2019-04-30 17:18发布

I have a struct:

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

My question is pretty simple. Is this the right way to access/modify shared memory? Is this the best approach?

(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.)

2条回答
做自己的国王
2楼-- · 2019-04-30 17:40

Yes, it is a way to create, then access or modify that shared memory. However, you may have sychronizaton issues, and you could use e.g. Posix semaphores for that. See first sem_overview(7) man page.

查看更多
姐就是有狂的资本
3楼-- · 2019-04-30 17:44

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.

查看更多
登录 后发表回答