shm.h
/*
this is the pathname of the server executable
remember to change it when the executable is moved to
other directory
*/
#define PATHNAME "/home/valletta/provecpp/shm/shmServer"
#define PROJECT 1
struct shared {
char data[256];
};
shmServer.c
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <stdlib.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include "shm.h"
struct shared *s = (void *)-1;
int shm_id = -1;
void server_exit(int ret);
int main()
{
key_t k;
if ( (k = ftok(PATHNAME,PROJECT)) == -1) {
perror("ftok");
server_exit(5);
}
shm_id = shmget( k , sizeof(struct shared), IPC_CREAT | IPC_EXCL | 0777);
if (shm_id == -1) {
perror("shmget");
server_exit(5);
}
printf("Shared memory id %d\n",shm_id);
if ( (s = shmat(shm_id, NULL , 0)) == (void *)-1) {
perror("shmat");
server_exit(5);
}
printf("Shared memory attached at %p\n",s);
sprintf(s->data,"Message from Server");
printf("Message put into shared memory\n");
server_exit(0);
}
void server_exit(int ret)
{
exit(ret); /* exit automatically detach any shm segment attached */
/* but we don't destroy it: we leave it for the client */
}
shmClient.c
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <stdlib.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include "shm.h"
struct shared *s = (void *)-1;
int shm_id = -1;
void client_exit(int ret);
int main()
{
key_t k;
if ( (k = ftok(PATHNAME,PROJECT)) == -1) {
perror("ftok");
client_exit(5);
}
if ((shm_id = shmget( k , sizeof(struct shared), 0777)) == -1) {
perror("shmget");
client_exit(5);
}
printf("Shared memory id %d\n",shm_id);
if ( (s = shmat(shm_id, NULL , 0)) == (void *)-1) {
perror("shmat");
client_exit(5);
}
printf("Shared memory attached at %p\n",s);
printf("s->data == %s\n",s->data);
client_exit(0);
}
void client_exit(int ret)
{
struct shmid_ds shds;
/* detach shared memory (exit() do this automatically) */
if (s != (void *)-1) shmdt(s);
/* mark shared memory segment as destroyed */
if (shm_id != -1) { shmctl(shm_id,IPC_RMID,&shds); }
exit(ret);
}
--
AntonioValletta - 10 Dec 2001