/*-------------------------------------------------------------------*/ /* testdupforkexec.c */ /* The dup, fork, and exec system calls. */ /*-------------------------------------------------------------------*/ #include #include #include #include #include int main(int argc, char *argv[]) { int iPid; printf("Parent process (%ld)\n", (long)getpid()); fflush(NULL); iPid = fork(); if (iPid == -1) {perror(argv[0]); return 1; } if (iPid == 0) { char *ppcArgv[2]; int iFd; int iRet; iFd = creat("tempfile", 0600); if (iFd == -1) {perror(argv[0]); exit(1); } iRet = close(1); if (iRet == -1) {perror(argv[0]); exit(1); } iRet = dup(iFd); if (iRet == -1) {perror(argv[0]); exit(1); } iRet = close(iFd); if (iRet == -1) {perror(argv[0]); exit(1); } ppcArgv[0] = "date"; ppcArgv[1] = NULL; execvp(ppcArgv[0], ppcArgv); perror(argv[0]); exit(1); } wait(NULL); /* This code is executed by only the parent process. */ printf("Parent process (%ld)\n", (long)getpid()); return 0; } /* Sample execution: $ gcc -Wall -ansi -pedantic -o testdupforkexec testdupforkexec.c $ testdupforkexec Parent process (25408) Parent process (25408) $ cat tempfile Sun Apr 25 18:49:31 EDT 2004 $ */