c - 共享内存编程错误(O_RDRW、PROT_WRITE、MAP_SHARED)

标签 c linux bash operating-system shared-memory

我正在尝试为共享内存对象运行程序。我的代码如下:

#include <stdio.h>  /*adding standard input output library*/
#include <stdlib.h> /*standard library for four variable types, several macros, and various functions for performing general functions*/
#include <string.h> /*adding string library*/
#include <sys/fcntl.h>  /* library for file control options */
#include <sys/shm.h> /*library for shared memory facility*/
#include <sys/stat.h> /*data returned by the stat() function*/
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 shm_fd;
    /* pointer to shared memory obect */
    void *ptr;
    /* create the shared memory object */
    shm_fd = shm_open(name, O_CREAT | O_RDRW, 0666);
    /* configure the size of the shared memory object */
    ftruncate(shm_fd, SIZE);
    /* memory map the shared memory object */
    ptr = mmap(0, SIZE, PROT_WRITE, MAP_SHARED, shm_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;
}

但是我得到以下错误

1.错误:

‘O_RDRW’ undeclared (first use in this function) shm_fd = shm_open(name, O_CREAT | O_RDRW, 0666);

2.错误:

‘PROT_WRITE’ undeclared (first use in this function) ptr = mmap(0, SIZE, PROT_WRITE, MAP_SHARED, shm_fd, 0);

3.错误:

‘MAP_SHARED’ undeclared (first use in this function) ptr = mmap(0, SIZE, PROT_WRITE, MAP_SHARED, shm_fd, 0);

还有这样的警告

note: each undeclared identifier is reported only once for each function it appears in

我试图找到 fctnl.hsham.hstat.h 并找到许多文件,但我尝试包含这些文件

#include "/usr/include/x86_64-linux-gnu/sys/fcntl.h" /*chose one file out of several options available*/
include "/usr/include/x86_64-linux-gnu/sys/shm.h" /*chose one file out of several options available*/
#include "/usr/include/x86_64-linux-gnu/sys/stat.h" /*chose one file out of several options available*/

但错误仍然存​​在。我正在使用 Ubuntu 16.04 LTS。在此先感谢您。

最佳答案

  1. #include <sys/mman.h>解决PROT_WRITE ;
  2. O_RDRW应该是 O_RDWR -“开放阅读和WRite”;
  3. #include <sys/mman.h>修复 MAP_SHARED错误;

关于c - 共享内存编程错误(O_RDRW、PROT_WRITE、MAP_SHARED),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46392368/

相关文章:

c - Magickwand C 改变图像颜色

c - 如何查询多个 pthread(子线程)以了解哪一个线程终止

java - 如何创建用于在 Java 中运行物理模拟的 Linux 集群?

http - 远程(Http)文件更改时如何执行操作?

c - 矩阵输入期间的段错误

c - C 的参数行选项解析

Linux 删除转义字符

linux - 通过 ssh 正确显示国际电子邮件字符

bash - 复制命令输出,将未处理后的副本打印到标准输出并将处理后的副本存储到文件中

bash - 关于在 rabbitmq 的 bash 脚本中使用 HOSTNAME