gpt4 book ai didi

c - 如何在 C 的共享内存中保存一个 int 和一个数组?

转载 作者:太空狗 更新时间:2023-10-29 17:22:33 29 4
gpt4 key购买 nike

我正在尝试编写一个程序,让子进程在 Linux 上相互通信。

这些进程都是从同一个程序创建的,因此它们共享代码。

我需要他们能够访问两个整型变量和一个整型数组。

我不知道共享内存是如何工作的,而且我搜索过的每一个资源都让我感到困惑。

如有任何帮助,我们将不胜感激!

编辑:这是我迄今为止编写的一些代码示例,只是为了共享一个 int,但它可能是错误的。

int segmentId;  
int sharedInt;
const int shareSize = sizeof(int);
/* Allocate shared memory segment */
segmentId = shmget(IPC_PRIVATE, shareSize, S_IRUSR | S_IWUSR);

/* attach the shared memory segment */
sharedInt = (int) shmat(segmentId, NULL, 0);

/* Rest of code will go here */

/* detach shared memory segment */
shmdt(sharedInt);
/* remove shared memory segment */
shmctl(segmentId, IPC_RMID, NULL);

最佳答案

您将需要增加共享内存的大小。你需要多大的阵列?无论它是什么值,您都需要在创建共享内存段之前选择它 - 动态内存在这里不会工作得很好。

当你附加到共享内存时,你会得到一个指向起始地址的指针。它将充分对齐以用于任何目的。因此,您可以沿着这些行创建指向您的两个变量和数组的指针(从您的代码示例中抄袭一些骨架)——注意使用指针访问共享内存:

enum { ARRAY_SIZE = 1024 * 1024 };
int segmentId;
int *sharedInt1;
int *sharedInt2;
int *sharedArry;

const int shareSize = sizeof(int) * (2 + ARRAY_SIZE);
/* Allocate shared memory segment */
segmentId = shmget(IPC_PRIVATE, shareSize, S_IRUSR | S_IWUSR);

/* attach the shared memory segment */
sharedInt1 = (int *) shmat(segmentId, NULL, 0);
sharedInt2 = sharedInt1 + 1;
sharedArry = sharedInt1 + 2;

/* Rest of code will go here */
...fork your child processes...
...the children can use the three pointers to shared memory...
...worry about synchronization...
...you may need to use semaphores too - but they *are* complex...
...Note that pthreads and mutexes are no help with independent processes...

/* detach shared memory segment */
shmdt(sharedInt1);
/* remove shared memory segment */
shmctl(segmentId, IPC_RMID, NULL);

关于c - 如何在 C 的共享内存中保存一个 int 和一个数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1671336/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com