/*--------------------------------------------------------------------*/ /* testdupforkexecpipe.c */ /* Author: Iasonas Petras */ /*--------------------------------------------------------------------*/ #include #include #include #include #include /*--------------------------------------------------------------------*/ /* Demonstrate the fork(), creat(), close(), pipe() and dup() system-level functions. 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]; enum {BUFFERSIZE=50}; char cbuffer[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 stdin (alies the read part of the pipe) */ (void) read(0, cbuffer, sizeof(cbuffer)); printf("Current date: %s (In Parent process %d)\n", cbuffer, getpid()); return 0; } /*--------------------------------------------------------------------*/ /* Sample execution: $ gcc217 testdupforkexecpipe.c -o testdupforkexecpipe $ ./testdupforkexecpipe 2018 parent Current date: Thu Dec 14 12:55:14 EST 2017 (In Parent process 2018) */