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