我正在使用信号量编写一些代码,包括进程之间的通信。我做了这样的结构:
typedef struct container {
sem_t resource, mutex;
int counter;
} container;
并以这种方式使用(在主应用程序中以及在从属进程中相同)
container *memory;
shm_unlink("MYSHM"); //just in case
fd = shm_open("MYSHM", O_RDWR|O_CREAT|O_EXCL, 0);
if(fd == -1) {
printf("Error");
exit(EXIT_FAILURE);
}
memory = mmap(NULL, sizeof(container), PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);
ftruncate(fd, sizeof(container));
当我使用 sem_ 函数之一时一切都很好,但是当我尝试做类似的事情时
memory->counter = 5;
这不起作用。可能我的指针出了问题,但我几乎尝试了所有方法,但似乎没有任何效果。也许有更好的方法在进程之间共享变量、结构等? 不幸的是,我不允许使用 boost 或类似的东西,该代码用于教育目的,我打算保持尽可能简单。
最佳答案
因为您在 shm_open()
之前使用 shm_unlink()
,所以您的两个进程永远不会打开同一个共享内存对象 - 每个进程都创建一个新的、不同的对象(即使它们具有相同的名称)。
不清楚您所说的“不起作用”是什么意思。以下基于您的代码的最小示例对我来说效果很好。它对你有什么作用?
#include <stdio.h>
#include <sys/mman.h>
#include <sys/types.h>
#include <fcntl.h>
#include <unistd.h>
#include <semaphore.h>
typedef struct container {
sem_t resource, mutex;
int counter;
} container;
int main()
{
container *memory;
int fd = shm_open("MYSHM", O_RDWR|O_CREAT|O_EXCL, 0);
if(fd == -1) {
perror("shm_open");
return 1;
}
ftruncate(fd, sizeof(container));
memory = mmap(NULL, sizeof(container), PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);
memory->counter = 5;
printf("%d\n", memory->counter);
return 0;
}
在检查您的代码时,它失败了,因为您尝试在 exec()
之后访问子进程中的文件描述符,并且 shm_open
设置了 FD_CLOEXEC默认情况下
标志,因此文件描述符不再在子进程中打开。因此,您只需在主进程中取消设置该标志(例如,在检查 shm_open
之后的错误后立即取消设置):
fdflags = fcntl(fd, F_GETFD);
fdflags &= ~FD_CLOEXEC;
fcntl(fd, F_SETFD, fdflags);
关于c - Mmap和结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2862027/