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"
key(ftokmay help with that), and you may also be required to roundsizeof(msg)up to a multiple ofsysconf(_SC_PAGESIZE). Beyond that: what is this doing that you did not expect it to do?msg=shm;leaks the carefully allocated memory; remove themalloc()line. Similarly in the client. The line(*msg).goal=64;would conventionally be writtenmsg->goal = 64;— the->operator was invented for a reason.main': 2048.c:(.text+0x45): multiple definition ofmain' /tmp/ccLsff3I.o:2048_client.c:(.text+0x0): first defined here 2048: In functionmove_board': (.text+0xaff): multiple definition ofmove_board' /tmp/ccNMeNPm.o:2048.c:(.text+0xa1b): first defined here And so on for all the other functions.