我正在使用一些代码,包括进程之间的通信,使用信号量.我做了这样的结构:
typedef struct container {
sem_t resource, mutex;
int counter;
} container;
Run Code Online (Sandbox Code Playgroud)
并以这种方式使用(在主应用程序中和从属进程中相同)
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));
Run Code Online (Sandbox Code Playgroud)
当我使用其中一个sem_函数时,一切都很好,但是当我尝试做类似的事情时
memory->counter = 5;
Run Code Online (Sandbox Code Playgroud)
它不起作用.可能我指针有问题,但我几乎尝试了一切,似乎没有任何工作.也许有更好的方法在流程之间共享变量,结构等?不幸的是,我不允许使用boost或类似的东西,代码用于教育目的,我想尽可能保持简单.
因为您shm_unlink()之前使用过shm_open(),所以您的两个进程永远不会打开相同的共享内存对象 - 每个进程都创建一个新的,不同的对象(即使它们具有相同的名称).
目前尚不清楚你的意思是"不起作用".以下基于您的代码的最小示例适用于我.它对你有什么用?
#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;
}
Run Code Online (Sandbox Code Playgroud)
在检查代码时,它失败了,因为您尝试在子进程之后访问文件描述符exec(),并默认shm_open设置FD_CLOEXEC标志,因此文件描述符不再在子进程中打开.所以你只需要在主进程中取消设置该标志(例如,在检查错误之后shm_open):
fdflags = fcntl(fd, F_GETFD);
fdflags &= ~FD_CLOEXEC;
fcntl(fd, F_SETFD, fdflags);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5462 次 |
| 最近记录: |