/*-------------------------------------------------------------------*/ /* testpipeforkexec.c */ /* The pipe system call with fork and exec. */ /*-------------------------------------------------------------------*/ #include #include #include #include FILE *fdopen(int fildes, const char *mode); #define BUFFER_LENGTH 256 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 iPid; int iRet; int piPipeFd[2]; FILE *psPipeRead; char pcBuffer[BUFFER_LENGTH]; 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) { char *ppcArgv[2]; ppcArgv[0] = "date"; ppcArgv[1] = NULL; iRet = close(piPipeFd[0]); if (iRet == -1) {perror(pcProgramName); return 1; } iRet = close(1); if (iRet == -1) {perror(pcProgramName); return 1; } iRet = dup(piPipeFd[1]); if (iRet == -1) {perror(pcProgramName); return 1; } iRet = close(piPipeFd[1]); if (iRet == -1) {perror(pcProgramName); return 1; } execvp("date", ppcArgv); perror(pcProgramName); exit(1); } atexit(waitForChild); iRet = close(piPipeFd[1]); if (iRet == -1) {perror(pcProgramName); return 1; } psPipeRead = fdopen(piPipeFd[0], "r"); if (psPipeRead == NULL) {perror(pcProgramName); return 1; } fgets(pcBuffer, BUFFER_LENGTH, psPipeRead); iRet = fclose(psPipeRead); if (iRet == EOF) {perror(pcProgramName); return 1; } printf("%s", pcBuffer); return 0; } /* Sample execution: --> gcc -Wall -ansi -pedantic -o testpipeforkexec testpipeforkexec.c --> testpipeforkexec Thu Jul 31 21:52:57 EDT 2003 --> */