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

我正在尝试编写一个程序,其中子进程在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); 

您将需要增加共享内存的大小。 你需要多大的arrays? 无论它是什么价值,你都需要在创建共享内存段之前选择它 – 动态内存在这里不会运行得太好。

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

 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); 

本指南看起来很有用: http : //www.cs.cf.ac.uk/Dave/C/node27.html 。 它包括一些示例程序。

还有在线Linux手册页 。

从您的评论看来,您似乎正在使用IPC_PRIVATE ,这看起来肯定是错误的(“私有”类型表明它不是为了共享,不是? – )。 尝试以下方法:

 #include  #include  ... int segid = shmget((key_t)0x0BADDOOD, shareSize, IPC_CREAT); if (segid < 0) { /* insert error processing here! */ } int *p = (int*) shmat(segid, 0, 0); if (!p) { /* insert error processing here! */ } 

共享内存只是一个进程分配的内存段,具有唯一的id,而另一个进程也将进行分配,具有相同的id,并且内存的大小是您正在使用的结构的大小,因此你会有一个2整数和整数数组的结构。

现在他们都有一个指向相同内存的指针,因此一个人的写入将覆盖其他任何内容,另一个人可以立即访问它。