/*--------------------------------------------------------------------*/ /* textforkexecwait.c */ /* Author: Bob Dondero */ /*--------------------------------------------------------------------*/ #include #include #include #include #include #include /*--------------------------------------------------------------------*/ /* Demonstrate the common way of using the fork(), exec(), and wait() system calls. Return 0. As usual, argc is the command-line argument count, and argv contains the command-line arguments. */ int main(int argc, char *argv[]) { pid_t iPid; for (;;) { fflush(NULL); iPid = fork(); if (iPid == -1) {perror(argv[0]); exit(EXIT_FAILURE); } if (iPid == 0) { /* This code is executed by only the child process. */ char *apcArgv[2]; apcArgv[0] = "date"; apcArgv[1] = NULL; execvp(apcArgv[0], apcArgv); perror(argv[0]); exit(EXIT_FAILURE); } /* This code is executed by only the parent process. */ /* Wait for the child process to finish. */ iPid = wait(NULL); if (iPid == -1) {perror(argv[0]); exit(EXIT_FAILURE); } /* Pause for a while. */ sleep(3); } /* Never should reach this point. */ } /*--------------------------------------------------------------------*/ /* Sample execution: $ gcc217 testforkexecwait.c -o testforkexecwait $ testforkexecwait Wed Dec 5 23:24:52 EST 2012 Wed Dec 5 23:24:55 EST 2012 Wed Dec 5 23:24:58 EST 2012 Wed Dec 5 23:25:01 EST 2012 Wed Dec 5 23:25:04 EST 2012 Wed Dec 5 23:25:07 EST 2012 Wed Dec 5 23:25:10 EST 2012 Wed Dec 5 23:25:13 EST 2012 Wed Dec 5 23:25:16 EST 2012 Wed Dec 5 23:25:19 EST 2012 Wed Dec 5 23:25:22 EST 2012 Wed Dec 5 23:25:25 EST 2012 Wed Dec 5 23:25:28 EST 2012 ^C */