-
Problems on shmem access
Hi there again!
It's me again and my newbie problems :P
I've been trying to read a string from a shared memory block but with no success.
I can read it OK if I use static name[] and content[] but I can't get anything using pointers.
I'm tired of playing around to get a solution. I give you some short versions. I run one.c then two.c
I'm sure it must be a newbie bug :S
onetwo.h
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/shm.h>
#define BUFFER_SLOTS 10
#define KEY 1919
typedef struct message {
int to, from, type;
char *name;
char *content;
} message;
typedef struct buffer {
int pos;
message msg[BUFFER_SLOTS];
} buffer;
one.c
Code:
#include "onetwo.h"
int main() {
buffer *BUF;
int bufshmid;
bufshmid = shmget(KEY, sizeof(struct buffer), 0666 | IPC_CREAT);
if ((BUF = shmat(bufshmid, NULL, 0)) == (buffer *)-1) {
printf("!!! could not attach to shared memory");
exit(1);
}
message *msg;
msg = malloc(sizeof(struct message));
msg->to = 1;
msg->from = 2;
msg->type = 3;
msg->name = malloc(strlen("hello")+1);
msg->content = malloc(strlen("world")+1);
strcpy(msg->name, "hello");
strcpy(msg->content, "world");
memcpy(&BUF->msg[0], msg, sizeof(struct message));
printf("all done\n");
sleep(5);
return 0;
}
two.c
Code:
#include "onetwo.h"
int main() {
buffer *BUF;
int bufshmid;
bufshmid = shmget(KEY, sizeof(struct buffer), 0666 | IPC_CREAT);
if ((BUF = shmat(bufshmid, NULL, 0)) == (buffer *)-1) {
printf("!!! could not attach to shared memory");
exit(1);
}
printf("type: %i\n", BUF->msg[0].type);
printf("name: %s\n", BUF->msg[0].name);
printf("all done\n");
return 0;
}
-
I suppose you want to read memory from two.c. First thing I noticed is the line
Code:
bufshmid = shmget(KEY, sizeof(struct buffer), 0666 | IPC_CREAT);
It creates the segment. For reading you should place instead
Code:
bufshmid = shmget(KEY, 0, 0);