vivek321
vivek321

Reputation: 199

Shared Memory programming errors(O_RDRW, PROT_WRITE,MAP_SHARED)

I am trying to run program for shared memory objects. My code as below:

#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;
}

But I am getting following errors

1.error:

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

2.error:

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

3.error:

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

And warnings like this

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

I tried to locate fctnl.h, sham.h, stat.h and found many files but i tried including this files

#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*/

But still error remains the same.I am using Ubuntu 16.04 LTS.Thanks in advance.

Upvotes: 1

Views: 3614

Answers (2)

Chuan
Chuan

Reputation: 441

  1. #include <sys/mman.h> to solve PROT_WRITE;
  2. O_RDRW should be O_RDWR - "open for read and WRite";
  3. #include <sys/mman.h> to fix MAP_SHARED error;

Upvotes: 7

Krassi Em
Krassi Em

Reputation: 192

#include <sys/mman.h> Please include in order to solve the PROT_WRITE

Upvotes: 2

Related Questions