/* NAME: shmreader SYNOPSIS: shmreader < inputfile DESCRIPTION: This program communicate with another program (shmwriter) using shared memory. This program reads the stdin into memory buffers and the shmwriter writes the buffers into stdout. */ #include "def.h" BUFFER *buf[2]; int shmid[2]; int emptybuf_sem, fullbuf_sem; int semaphore =1; /* It allows me to turn on and off the use of semaphores*/ main() { int i; /* creat the shared memory segments and attach them */ for (i = 0; i < 2; i++) { if ( (shmid[i] = shmget(SHMKEY + i, sizeof(BUFFER), PERMS | IPC_CREAT)) < 0) printf("server: can't get shared memory %d", i); if ( (buf[i] = (BUFFER *) shmat(shmid[i], (char *) 0, 0)) == (BUFFER *) -1) printf("server: can't attach shared memory %d", i); } /* create the two semaphores */ if ( (fullbuf_sem = sem_create(SEMKEY1, 0)) < 0) printf("server: can't create client semaphore"); if ( (emptybuf_sem = sem_create(SEMKEY2, 2)) < 0) printf("server: can't create server semaphore"); /* raed from stdin and write to memory */ reader(); /* detach this shared memory and close the semaphores. the other program (shmwriter) is the last one to use the shared memory, so it'll remove it when it's done */ for (i = 0; i < 2; i++) { if (shmdt((void *) buf[i]) < 0) printf("server: can't detach shared memory "); } sem_close(emptybuf_sem); sem_close(fullbuf_sem); exit(0); } reader() { int i=0; while (1) { if (semaphore) sem_wait(emptybuf_sem); buf[i]->size = read(0, buf[i]->data, BSIZE); if (semaphore) sem_signal(fullbuf_sem); /* printf("Sending buffer of size = %d\n",buf[i]->size);*/ if (buf[i]->size <=0) return; i ^= 1; } }