【发布时间】: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
谁能帮我知道为什么共享内存失败?!?
【问题讨论】:
-
您可能会发现ESR 的优秀文章How To s The Smart Way 很有帮助。
标签: c posix shared-memory fibonacci