Basic shared memory program in C

Posted by nicopuri on Stack Overflow See other posts from Stack Overflow or by nicopuri
Published on 2010-05-11T11:49:15Z Indexed on 2010/05/11 11:54 UTC
Read the original article Hit count: 243

Filed under:
|

Hi,

I want to make a basic chat application in C using Shared memory. I am working in Linux. The application consist in writing the client and the server can read, and if the server write the client can read the message.

I tried to do this, but I can't achieve the communication between client and server. The code is the following:

Server.c

int

main(int argc, char **argv) { char *msg; static char buf[SIZE]; int n;

msg = getmem(); memset(msg, 0, SIZE); initmutex();

while ( true ) { if( (n = read(0, buf, sizeof buf)) > 0 ) { enter(); sprintf(msg, "%.*s", n, buf); printf("Servidor escribe: %s", msg); leave(); }else{ enter(); if ( strcmp(buf, msg) ) { printf("Servidor lee: %s", msg); strcpy(buf, msg); } leave(); sleep(1); } } return 0; }

Client.c

int main(int argc, char **argv) { char *msg; static char buf[SIZE-1]; int n;

msg = getmem(); initmutex();

while(true) { if ( (n = read(0, buf, sizeof buf)) > 0 ) { enter(); sprintf(msg, "%.*s", n, buf); printf("Cliente escribe: %s", msg); leave(); }else{ enter(); if ( strcmp(buf, msg) ) { printf("Cliente lee: %s", msg); strcpy(buf, msg); } leave(); sleep(1); } } printf("Cliente termina\n"); return 0; }


The shared memory module is the folowing:

#include "common.h"

void fatal(char *s) { perror(s); exit(1); }

char * getmem(void) { int fd; char *mem;

if ( (fd = shm_open("/message", O_RDWR|O_CREAT, 0666)) == -1 ) fatal("sh_open"); ftruncate(fd, SIZE); if ( !(mem = mmap(NULL, SIZE, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0)) ) fatal("mmap"); close(fd); return mem; }

static sem_t *sd;

void initmutex(void) { if ( !(sd = sem_open("/mutex", O_RDWR|O_CREAT, 0666, 1)) ) fatal("sem_open"); }

void enter(void) { sem_wait(sd); }

void leave(void) { sem_post(sd); }

© Stack Overflow or respective owner

Related posts about shared-memory

Related posts about c