/*------------------------------------------------------------------*/ /* testdupforkexec.c */ /* Author: Bob Dondero */ /* The dup, fork, and exec system calls. */ /*------------------------------------------------------------------*/ #include #include #include #include #include int main(int argc, char *argv[]) { pid_t iPid; printf("Parent process (%d)\n", (int)getpid()); fflush(NULL); iPid = fork(); if (iPid == -1) {perror(argv[0]); return EXIT_FAILURE; } if (iPid == 0) { char *ppcArgv[2]; int iFd; int iRet; iFd = creat("tempfile", 0600); if (iFd == -1) {perror(argv[0]); exit(EXIT_FAILURE); } iRet = close(1); if (iRet == -1) {perror(argv[0]); exit(EXIT_FAILURE); } iRet = dup(iFd); if (iRet == -1) {perror(argv[0]); exit(EXIT_FAILURE); } iRet = close(iFd); if (iRet == -1) {perror(argv[0]); exit(EXIT_FAILURE); } ppcArgv[0] = "date"; ppcArgv[1] = NULL; execvp(ppcArgv[0], ppcArgv); perror(argv[0]); exit(EXIT_FAILURE); } iPid = wait(NULL); if (iPid == -1) {perror(argv[0]); return EXIT_FAILURE; } /* This code is executed by only the parent process. */ printf("Parent process (%d)\n", (int)getpid()); return 0; } /*------------------------------------------------------------------*/ /* Sample execution: $ gcc -Wall -ansi -pedantic testdupforkexec.c -o testdupforkexec $ testdupforkexec Parent process (4762) Parent process (4762) $ cat tempfile Sat Nov 17 18:29:12 EST 2007 */