weixin_45807495 2019-10-28 18:29 采纳率: 0%
浏览 393

用posix共享内存api,报错segmentation fault(core dump)

按照《操作系统概念》第十版上面照抄下来的,不知道为什么会报错

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <sys/shm.h> 
#include <sys/stat.h>

#include <sys/mman.h>
int main() {
/* the size (in bytes) of shared memory object */
const int SIZE = 4096; 
/* name of the shared memory object */
const char *name = "OS";
/* strings written to shared memory */ 
const char *message 0 = "Hello";
const char *message 1 = "World!";
/* shared memory file descriptor */
int fd;
/* pointer to shared memory obect */ 
char *ptr;

/* create the shared memory object */
    fd = shm open(name,O CREAT | O RDWR,0666);
/* configure the size of the shared memory object */
    ftruncate(fd, SIZE);
/* memory map the shared memory object */ 
    ptr = (char *) mmap(0, SIZE, PROT READ | PROT WRITE, MAP SHARED, fd, 0);
/* write to the shared memory object */ 
    sprintf(ptr,"%s",message 0);
    ptr += strlen(message 0); 
    sprintf(ptr,"%s",message 1); 
    ptr += strlen(message 1);
return 0;
}

Figure 3.16 Producer process illustrating POSIX shared-memory API.

#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h> 
#include <sys/shm.h> 
#include <sys/stat.h>

#include <sys/mman.h>
int main() {
/* the size (in bytes) of shared memory object */ 
const int SIZE = 4096; 
/* name of the shared memory object */
const char *name = "OS";
/* shared memory file descriptor */ 
int fd; 
/* pointer to shared memory obect */ 
char *ptr;

/* open the shared memory object */
    fd = shm open(name, O RDONLY, 0666);
/* memory map the shared memory object */ 
    ptr = (char *) mmap(0, SIZE, PROT READ | PROT WRITE, MAP SHARED, fd, 0);
/* read from the shared memory object */ 
    printf("%s",(char *)ptr);
/* remove the shared memory object */ 
    shm unlink(name);
    return 0;
}

Consumer process illustrating POSIX shared-memory API.

报错信息是这样的,先运行生产者,再运行消费者,就报错了

图片说明

  • 写回答

1条回答

  • bobhuang 2019-10-28 18:45
    关注

    每一步都要检查是否成功,否则很容易出问题。比如这里:
    mmap(0, SIZE, PROT READ | PROT WRITE, MAP SHARED, fd, 0);
    有可能因为前后两次的SIZE不一样,导致map失败。

    评论

报告相同问题?

悬赏问题

  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?