共享内存编程错误(O_RDRW,PROT_WRITE,MAP_SHARED)

时间:2017-09-24 16:37:21

标签: 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.error:

  

'O_RDRW'未声明(首次使用此功能)             shm_fd = shm_open(name,O_CREAT | O_RDRW,0666);

2.error:

  

'PROT_WRITE'未声明(首次使用此功能)             ptr = mmap(0,SIZE,PROT_WRITE,MAP_SHARED,shm_fd,0);

3.error:

  

'MAP_SHARED'未声明(首次使用此功能)             ptr = mmap(0,SIZE,PROT_WRITE,MAP_SHARED,shm_fd,0);

这样的警告

  

注意:每个未声明的标识符仅报告一次   功能出现在

我尝试找到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。提前致谢。

2 个答案:

答案 0 :(得分:2)

  1. #include <sys/mman.h>解决PROT_WRITE;
  2. O_RDRW应为O_RDWR - &#34;可供阅读并WRite&#34 ;;
  3. #include <sys/mman.h>修复MAP_SHARED错误;

答案 1 :(得分:1)

#include <sys/mman.h> 请包括以解决PROT_WRITE