【问题标题】:shared memory between parent and child in cc语言中父子共享内存
【发布时间】:2015-11-15 23:56:37
【问题描述】:

我正在使用生成斐波那契序列的 fork() 编写程序,因此如果我在命令行中传递 8,则输出为: 0、1、1、2、3、5、8、13、21 并有这个输出

下一步我正在尝试使用 Posix 共享内存在父子之间共享它,但是它们之间没有共享数据,这是我的代码:

      pid = fork();
      if (pid == 0)
      {  /* create the shared memory object */
     shm_fib = shm_open(name, O_CREAT | O_RDWR, 0666);

     /* configure the size of the shared memory object */
     ftruncate(shm_fib, SIZE);
     /* memory map the shared memory object */
     ptr = mmap(0, SIZE, PROT_WRITE, MAP_SHARED, shm_fib, 0);
         printf("Child is producing the Fibonacci Sequence...\n");
         sprintf(ptr,"%d, %d,",f1,f2);
         ptr++;
         for (i=2;i<n;i++)
         {
            sum=f1+f2;
            sprintf(ptr,"%d, ", sum);
            ptr++;
            f1=f2;
            f2=sum;
         }
         printf("Child ends\n"); 
      }
      else 
      {  wait(NULL);
         /* open the shared memory object */
         shm_fib = shm_open(name, O_RDONLY, 0666); 

         if (shm_fib == -1) 
         {

        printf("shared memory failed\n");

        exit(-1);

     }
     /* memory map the shared memory object */
     ptr = mmap(0, SIZE, PROT_READ, MAP_SHARED, shm_fib, 0);
         printf("Parent is waiting for child to complete...\n");

         /* read from the shared memory object */
     printf("%s",(char *)ptr);
     /* remove the shared memory object */
     shm_unlink(name);
         printf("Parent ends\n");
      }

这是输出:

plz, Enter the value of number to show the fibonacci sequence:
9
Child is producing the Fibonacci Sequence...
Child ends
shared memory failed

谁能帮我知道为什么共享内存失败?!?

【问题讨论】:

标签: c posix shared-memory fibonacci


【解决方案1】:

始终打印出errno 或致电perror 以查看确切的错误。这将告诉您错误是“没有这样的文件或目录”。这是由代码末尾的shm_unlink 引起的。 shm_unlink 可以(并且经常)在父级有机会完成共享内存的使用之前由子级执行。如果不明显,手册页中会提到shm_unlink

成功 shm_unlink() 后,尝试 shm_open() 一个对象 同名会失败

建议您删除该代码。不要认为它是必需的,因为父进程代码已经有一个(更有效的)shm_unlink

更新:事实上,shm_unlink 保证在父级使用共享内存之前被执行。因为父母(正确地)有一个wait 供孩子完成。

【讨论】:

  • 非常感谢,但在我更改 shm_unlink 之前问题仍然存在,所以我尝试将父进程中的 sprintf 语句从:sprintf(ptr,"%d, %d," ,f1,f2);指针++;为每个值分开并且正确共享
【解决方案2】:

当您正在分叉而不是执行时,您可以在分叉之前简单地 mmapMAP_ANONYMOUS(或使用 /dev/zeroMAP_SHARED 映射。该区域将在两个进程之间共享:

// Error handling omitted for brevity
void* ptr = mmap(0, SIZE, PROT_READ | PROT_WRITE, MAP_SHARED, -1, 0);
pid_t pid = fork();
if (pid == 0) {
  // [...] Write the shared memory
} else {
  wait(NULL);
  // [...] Read the shared memory
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-01-01
    • 2011-05-15
    • 2023-02-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-27
    相关资源
    最近更新 更多