/* shmwriter is part of the CopyFile. It is the child process that writes the buffers into stdout. */ #include "def.h" BUFFER *buf[2]; int shmid[2]; int semaphore =0; /* it allows me to turn on and off the use of semaphores*/ int emptybuf_sem, fullbuf_sem; main() { int i; /* get the shared memory segments and attach it the parent must have already created it */ for (i = 0; i < 2; i++) { if ( (shmid[i] = shmget(SHMKEY + i, sizeof(BUFFER), 0 )) < 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); } /* open the two semaphores. The parent must have already created it */ if ( (fullbuf_sem = sem_open(SEMKEY1)) < 0) printf("server: can't open full semaphore"); if ( (emptybuf_sem = sem_open(SEMKEY2)) < 0) printf("server: can't create empty semaphore"); writer(); /* * Detach and remove the shared memory segments and * close the semaphores. */ for (i = 0; i < 2; i++) { if (shmdt(buf[i]) < 0) printf("client: can't detach shared memory "); if (shmctl(shmid[i], IPC_RMID, (struct shmid_ds *) 0) < 0) printf("client: can't remove shared memory "); } /* sem_close(fullbuf_sem); sem_close(emptybuf_sem);*/ sem_rm(fullbuf_sem); sem_rm(emptybuf_sem); exit(0); } writer() { int i=0; while (1) { if (semaphore) sem_wait(fullbuf_sem); printf("buff length =%d\n",buf[i]->size);fflush(stdout); write(1, buf[i]->data, buf[i]->size); if (buf[i]->size<=0) return; if (semaphore) sem_signal(emptybuf_sem); i ^= 1; } }