/*-------------------------------------------------------------------*/ /* testpipe.c */ /* The pipe system call. */ /*-------------------------------------------------------------------*/ #include #include #include #include #define BUFFER_SIZE 100 int main(int argc, char *argv[]) { int piPipeFd[2]; int iProducerPid; int iConsumerPid; int iRet; iRet = pipe(piPipeFd); if (iRet == -1) {perror(argv[0]); return 1; } fflush(NULL); iProducerPid = fork(); /* Fork a producer child. */ if (iProducerPid == -1) {perror(argv[0]); return 1; } if (iProducerPid == 0) { /* Producer child */ char pcBuffer[] = "somedata\n"; int iBytesWritten = 0; iRet = close(piPipeFd[0]); if (iRet == -1) {perror(argv[0]); exit(1); } while (iBytesWritten < 9) { iRet = write(piPipeFd[1], pcBuffer + iBytesWritten, 9 - iBytesWritten); if (iRet == -1) {perror(argv[0]); exit(1); } iBytesWritten += iRet; } iRet = close(piPipeFd[1]); if (iRet == -1) {perror(argv[0]); exit(1); } exit(0); } iRet = close(piPipeFd[1]); if (iRet == -1) {wait(NULL); perror(argv[0]); return 1; } fflush(NULL); iConsumerPid = fork(); /* Fork a consumer child. */ if (iConsumerPid == -1) {wait(NULL); perror(argv[0]); return 1; } if (iConsumerPid == 0) { /* Consumer child */ char pcBuffer[BUFFER_SIZE]; int iBytesRead = 0; int i; while (iBytesRead < 9) { iRet = read(piPipeFd[0], pcBuffer + iBytesRead, 9 - iBytesRead); if (iRet == -1) {perror(argv[0]); exit(1); } iBytesRead += iRet; } iRet = close(piPipeFd[0]); if (iRet == -1) {perror(argv[0]); exit(1); } /* Print the data to make sure it was communicated properly. */ for (i = 0; i < 9; i++) putchar(pcBuffer[i]); exit(0); } iRet = close(piPipeFd[0]); if (iRet == -1) {wait(NULL); wait(NULL); perror(argv[0]); return 1; } wait(NULL); wait(NULL); return 0; } /* Sample execution: $ gcc -Wall -ansi -pedantic -o testpipe testpipe.c $ testpipe somedata $ */