gpt4 book ai didi

c - 将 posix 信号量数组分配给共享内存

转载 作者:太空宇宙 更新时间:2023-11-04 03:59:23 25 4
gpt4 key购买 nike

我想将一组未命名的信号量写入共享内存,以便我可以在 fork 进程中访问它们。这是我到目前为止所拥有的:

int main(int argc, char *argv[]){

int num_process = atoi(argv[1]);
int i = 0;

int ppid = getpid();
void *addr;

int numsems = 512;
int object_size = numsems * sizeof(sem_t);

printf("declaring semaphores\n");
sem_t *sem[numsems];

//create shared memory and check that it worked
printf("opening shared memory\n");
int shmem_fd = shm_open("/my_shmem", O_CREAT | O_RDWR, S_IRUSR | S_IWUSR);

if(shmem_fd == -1){
perror("Can't open shmem object");
exit(-1);
}

//truncate memory object
if(ftruncate(shmem_fd, object_size) == -1){
perror("failed to resize shmem object");
exit(-1);
}

addr = mmap(NULL, object_size, PROT_READ | PROT_WRITE, MAP_SHARED, shmem_fd, 0);

if(MAP_FAILED == addr){
perror("Map failed");
exit(-1);
}

//store the semaphores at the start
printf("initializing semaphores\n");

for(i = 0; i<numsems; i++){
sem[i] = addr + i*sizeof(sem_t);
if(sem_init(sem[i], 1, 0) == -1){
perror("sem_init failed");
exit(-1);
}
}

//create children
while((getpid() == ppid) && (i < num_process)){


switch(fork()){
case -1:
printf("fork %d failed\n", i);
break;

case 0:
//child process
printf("child created\n");
child_program( sem, numsems);
printf("child done\n");
break;

default: //parent continues on to create next child
break;

}
i++;
}
}

编译正常,但当我尝试运行它时,当它到达 sem_t *sem[numsems] 部分时出现段错误。我在别处读到你不应该创建一个指向信号量的指针,但是当我没有这样做并尝试 &sem = addr 时,我得到了一个关于需要左值的错误。任何帮助将不胜感激。

最佳答案

首先,为什么不在父进程中创建(并映射)共享内存段,然后在子进程中打开呢?

而且,为什么不简单地映射整个数组而不使用指针,而不是指针数组:

家长:

sem_t *sem;

shm_open("/my_shmem", O_CREAT | O_RDWR ...);

sem = mmap(NULL, object_size, ...);

child :

semt_t *sem;

shm_open("/my_shmem", O_RDWR, 0);

sem = mmap(NULL, object_size, ...);

关于c - 将 posix 信号量数组分配给共享内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13446991/

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