子进程在相同的内存地址中创建结构

问题描述

这是我功能的开始。我有一个父流程,该流程创建了多个调用此生产者功能的子流程。当我的打印语句输出为我提供完全相同的内存地址时,我希望每个p_shm_recv_buf结构对于该过程而言都是唯一的。我不确定这里出了什么问题。

int producer( int id,ISTACK * buffer,int BUFFER_SIZE,sem_vars* sems,int image_num ) {
    printf("[Creation] Producer %d created\n",id);
    curl_global_init(CURL_GLOBAL_DEFAULT);
    while (buffer->next_prod < 50) {

        // Create our receive buffer
        RECV_BUF *p_shm_recv_buf;
        int shm_size = sizeof_shm_recv_buf(BUF_SIZE);
        int shmid = shmget(IPC_PRIVATE,shm_size,IPC_CREAT | IPC_EXCL | S_IRUSR | S_IWUSR);
        if ( shmid == -1 ) {
            perror("shmget");
            abort();
        }
        printf("[LOG1] buf address at %p\n",p_shm_recv_buf->buf);
        p_shm_recv_buf = shmat(shmid,NULL,0);
        printf("[LOG2] buf address at %p\n",p_shm_recv_buf->buf);
        shm_recv_buf_init(p_shm_recv_buf,BUF_SIZE);

输出

shm_size = 44.
sem_size = 104.
[Creation] Producer 0 created
[Creation] Producer 1 created
[Creation] Producer 2 created
[Creation] Consumer 5 created
[Creation] Consumer 3 created
[Creation] Consumer 4 created
[LOG1] buf address at 0x7ffefa2d8ca0
[LOG2] buf address at (nil)
[LOG3] buf address at 0x7fe4a879c020
Producer 0 working ... 
[LOG1] buf address at 0x7ffefa2d8ca0
[LOG2] buf address at (nil)
[LOG3] buf address at 0x7fe4a879c020
Producer 1 working ... 
[LOG1] buf address at 0x7ffefa2d8ca0
[LOG2] buf address at (nil)
[LOG3] buf address at 0x7fe4a879c020

解决方法

每个过程都有完整的“虚拟”内存映射。

请记住,子进程是父进程的副本。

因此希望具有相同的“虚拟”内存地址