用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.

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

图片说明

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