/*-------------------------------------------------------------------*/ /* testpipeparent2child.c */ /* The pipe system call. */ /*-------------------------------------------------------------------*/ #include #include #include #include FILE *fdopen(int fildes, const char *mode); #define BUFFER_LENGTH 100 static const char *pcProgramName = NULL; void waitForChild(void) { int iRet; iRet = wait(NULL); if (iRet == -1) perror(pcProgramName); } int main(int argc, char *argv[]) { int piPipeFd[2]; FILE *psPipeWrite; int iPid; int iRet; pcProgramName = argv[0]; iRet = pipe(piPipeFd); if (iRet == -1) {perror(pcProgramName); return 1; } fflush(NULL); iPid = fork(); if (iPid == -1) {perror(pcProgramName); return 1; } if (iPid == 0) { FILE *psPipeRead; char pcBuffer[BUFFER_LENGTH]; iRet = close(piPipeFd[1]); if (iRet == -1) {perror(pcProgramName); exit(1); } psPipeRead = fdopen(piPipeFd[0], "r"); if (psPipeRead == NULL) {perror(pcProgramName); exit(1); } iRet = fscanf(psPipeRead, "%s", pcBuffer); if (iRet == EOF) {perror(pcProgramName); exit(1); } printf("%s\n", pcBuffer); iRet = fclose(psPipeRead); if (iRet == EOF) {perror(pcProgramName); exit(1); } exit(0); } atexit(waitForChild); iRet = close(piPipeFd[0]); if (iRet == -1) {perror(pcProgramName); return 1; } psPipeWrite = fdopen(piPipeFd[1], "w"); if (psPipeWrite == NULL) {perror(pcProgramName); return 1; } fprintf(psPipeWrite, "somedata\n"); fflush(NULL); fclose(psPipeWrite); return 0; } /* Sample execution: --> gcc -Wall -ansi -pedantic -o testpipeparent2child testpipeparent2child.c --> testpipeparent2child somedata --> */