/*--------------------------------------------------------------------*/ /* testpipewrapfile.c */ /* Author: Iasonas Petras */ /*--------------------------------------------------------------------*/ #define _POSIX_SOURCE 1 /* for fdopen */ #include #include #include #include #include /*--------------------------------------------------------------------*/ /* Demonstrate the fork(), creat(), close(), pipe() and dup() system-level functions when you wrap a file around a pipe. As usual, argc is the command-line argument count, and argv contains the command-line arguments. Return 0. */ int main(int argc, char *argv[]) { pid_t iPid; int iRet; int ChildToParent[2]; FILE *psFileChildToParent; enum {BUFFERSIZE=50}; char pcDay[BUFFERSIZE], pcYear[BUFFERSIZE], pcMonth[BUFFERSIZE], pcNumDay[BUFFERSIZE], pcTime[BUFFERSIZE]; printf("%d parent\n", (int)getpid()); if(pipe(ChildToParent)) {perror(argv[0]); exit(EXIT_FAILURE); } iRet = fflush(NULL); if (iRet == EOF) {perror(argv[0]); exit(EXIT_FAILURE); } iPid = fork(); if (iPid == -1) {perror(argv[0]); exit(EXIT_FAILURE); } if (iPid == 0) { char *apcArgv[2]; int iRet; /* Redirect stdout to the "out part" of the pipe */ iRet = close(1); if (iRet == -1) {perror(argv[0]); exit(EXIT_FAILURE); } iRet = dup(ChildToParent[1]); if (iRet == -1) {perror(argv[0]); exit(EXIT_FAILURE); } /* Close the pipe */ iRet = close(ChildToParent[0]); if (iRet == -1) {perror(argv[0]); exit(EXIT_FAILURE); } iRet = close(ChildToParent[1]); if (iRet == -1) {perror(argv[0]); exit(EXIT_FAILURE); } apcArgv[0] = "date"; apcArgv[1] = NULL; execvp("date", apcArgv); perror(argv[0]); exit(EXIT_FAILURE); } iPid = wait(NULL); if (iPid == -1) {perror(argv[0]); exit(EXIT_FAILURE); } /* This code is executed by only the parent process. */ iRet = close(ChildToParent[1]); if (iRet == -1) {perror(argv[0]); exit(EXIT_FAILURE); } iRet = close(0); if (iRet == -1) {perror(argv[0]); exit(EXIT_FAILURE); } iRet = dup(ChildToParent[0]); if (iRet == -1) {perror(argv[0]); exit(EXIT_FAILURE); } iRet = close(ChildToParent[0]); if (iRet == -1) {perror(argv[0]); exit(EXIT_FAILURE); } /* Read in a string from the pipe */ psFileChildToParent = fdopen(0, "r"); fscanf(psFileChildToParent, "%s %s %s %s EST %s", pcDay, pcMonth, pcNumDay, pcTime, pcYear); printf("Day: %s\n", pcDay); printf("Month: %s\n", pcMonth); printf("NumDay: %s\n", pcNumDay); printf("Time: %s\n", pcTime); printf("Year: %s\n", pcYear); fclose(psFileChildToParent); return 0; } /*--------------------------------------------------------------------*/ /* Sample execution: $ gcc217 testpipewrapfile.c -o testpipewrapfile $ ./testpipewrapfile 26247 parent Day: Mon Month: Dec NumDay: 11 Time: 18:46:15 Year: 2017 */