简体   繁体   English

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

[英]Assigning an array of posix semaphores to shared memory

I would like to write an array of unnamed semaphores to shared memory so I can access them in forked processes. 我想将一个未命名信号量数组写入共享内存,以便可以在派生进程中访问它们。 Here's what I have so far: 这是我到目前为止的内容:

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++;
}
}

Which compiles fine but when I try to run it I get a segmentation fault when it gets to the sem_t *sem[numsems] part. 哪个可以很好地编译,但是当我尝试运行它时,当它到达sem_t *sem[numsems]部分时会遇到分段错误。 I've read elsewhere that you shouldn't create a pointer to semaphores but when I didn't and tried &sem = addr I got an error about needing a lvalue. 我在其他地方读过,您不应该创建指向信号量的指针,但是当我没有尝试并尝试&sem = addr ,出现有关需要左值的错误。 Any help would be much appreciated. 任何帮助将非常感激。

First of all, why not create (and map) the shared memory segment in the parent process, and then open it in the child? 首先,为什么不在父进程中创建(并映射)共享内存段,然后在子进程中打开它?

And also, instead of having an array of pointer, why not simply map the whole array, without using pointers: 而且,为什么不使用指针数组而不是简单地映射整个数组而不使用指针:

Parent: 家长:

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, ...);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM