Syn
Syn

Reputation: 776

Using shared memory in C

I would like to create a server-client program in which the two processes pass information between each other using shared memory

information to be passed:

typedef struct shared_mem{
int board[BOARD_SIZE * BOARD_SIZE];
int goal;
}shared_mem;
shared_mem *msg;

server:

int main(int argc, char **argv) {

int shmid;
key_t key=ftok("2048_client", 42);
if(key == -1) {
        printf("ftok failed");
        return -1;
    }


shared_mem *shm;
msg=(shared_mem *)malloc(sizeof(shared_mem));

/*
     * Create the segment
    */
    if ((shmid = shmget(key, sizeof(msg), IPC_CREAT)) < 0) {
        perror("shmget");
        exit(1);
    }

    /*
    * Now we attach the segment to our data space.
    */
  if ((shm = shmat(shmid, NULL, 0)) == (char *) -1) {
        perror("shmat");
        exit(1);
    }

msg=shm;

(*msg).goal=64;
}

client:

int main(int argc, char **argv) {

int shmid;
key_t key=ftok("2048_client", 42);
if(key == -1) {
        printf("ftok failed");
        return -1;
    }
shared_mem *shm;
msg=(shared_mem *)malloc(sizeof(shared_mem));
/*
     * Create the segment.
    */
    if ((shmid = shmget(key, sizeof(msg), 0)) < 0) {
        perror("shmget");
        exit(1);
    }

    /*
    * Now we attach the segment to our data space.
    */
  if ((shm = shmat(shmid, NULL, 0)) == (char *) -1) {
        perror("shmat");
        exit(1);
    }

msg=shm;
printf("dscsadc:  %d",msg->goal);
   }

I am new to shared memory and i would like to understand why it doesn't work and how it is supposed to work. I am getting "shmat: Permission denied"

Upvotes: 2

Views: 5012

Answers (2)

Jonathan Leffler
Jonathan Leffler

Reputation: 753725

The problem is that you create the shared memory segment with 0000 permissions, so no-one can read or write it.

Change the shmget() call from:

if ((shmid = shmget(key, sizeof(msg), IPC_CREAT)) < 0) {

to:

if ((shmid = shmget(key, sizeof(msg), IPC_CREAT|0600)) < 0) {

Only the user running the program can access the shared memory that is created.

Note that POSIX shmget() says:

  • The low-order nine bits of shm_perm.mode are set to the low-order nine bits of shmflg.

Upvotes: 2

Andro
Andro

Reputation: 2232

If you're not limited to C only, look at the boost library. It enables you to create shared memory segments for interprocess communication.

using boost::interprocess;
shared_memory_object shm_obj
   (create_only,                  //only create
   "shared_memory",              //name
   read_write                   //read-write mode
   );

http://www.boost.org/doc/libs/1_54_0/doc/html/interprocess/sharedmemorybetweenprocesses.html

Other then that, you can always use pipes, or if you're thinking about windows - COM.

Upvotes: 0

Related Questions