我想将一组未命名的信号量写入共享内存,这样我就可以在分叉的进程中访问它们。这是我到目前为止所拥有的:
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
我得到了一个关于需要左值的错误。任何帮助将非常感激。