/* NAME: FileCopy SYNOPSIS: FileCopy < inputfile > outputfile DESCRIPTION: This program commuincate 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; main() { int i; int status; pid_t pid; /* 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) perror("server: can't get shared memory %d", i); if ( (buf[i] = (BUFFER *) shmat(shmid[i], (char *) 0, 0)) == (BUFFER *) -1) perror("server: can't attach shared memory %d", i); } /* create the two semaphores */ if ( (fullbuf_sem = sem_create(SEMKEY1, 1)) < 0) perror("server: can't create client semaphore"); if ( (emptybuf_sem = sem_create(SEMKEY2, 0)) < 0) perror("server: can't create server semaphore"); /* fork a child to read from memory and write to stdout */ if ( (pid = fork()) < 0) perror("fork error"); else if (pid == 0) { sleep (1); if (execl ("./shmWriter", "shmwriter", NULL) < 0){ perror("exec error"); exit (-1); } } else /* the parent raed from stdin and write to memory */ reader(); /* wait for the child to finish writing the memory buffers */ if (wait(&status) !=pid ) perror("wait error"); /* detach ths shared memory and close the semahpores. 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(buf[i]) < 0) perror("server: can't detach shared memory "); } sem_close(emptybuf_sem); sem_close(fullbuf_sem); exit(0); } reader() { int i=0; sem_signal(emptybuf_sem); sem_signal(emptybuf_sem); while (1) { sem_wait(emptybuf_sem); buf[i]->size = read(0,buf[i]->data, BSIZE); sem_signal(fullbuf_sem); if (buf[i]->size <=0) break; i ^= 1; } }