/*--------------------------------------------------------------------*/ /* textforkexecwait.c */ /* Author: Bob Dondero */ /*--------------------------------------------------------------------*/ #include #include #include #include #include /*--------------------------------------------------------------------*/ /* Demonstrate the common pattern of using the system-level fork(), execvp(), and wait() functions. Return 0. As usual, argc is the command-line argument count, and argv contains the command-line arguments. */ int main(int argc, char *argv[]) { enum {SLEEP_SECONDS = 3}; pid_t iPid; int iRet; for (;;) { iRet = fflush(stdin); if (iRet == EOF) {perror(argv[0]); exit(EXIT_FAILURE); } iRet = fflush(stdout); if (iRet == EOF) {perror(argv[0]); exit(EXIT_FAILURE); } iPid = fork(); if (iPid == -1) {perror(argv[0]); exit(EXIT_FAILURE); } if (iPid == 0) { /* This code is executed by the child process only. */ char *apcArgv[2]; apcArgv[0] = "date"; apcArgv[1] = NULL; execvp("date", apcArgv); perror(argv[0]); exit(EXIT_FAILURE); } /* This code is executed by the parent process only. */ /* Wait for the child process to exit. */ iPid = wait(NULL); if (iPid == -1) {perror(argv[0]); exit(EXIT_FAILURE); } /* Pause for SLEEP_SECONDS seconds. */ sleep(SLEEP_SECONDS); } /* Should not reach this point. */ } /*--------------------------------------------------------------------*/ /* Sample execution: $ gcc217 testforkexecwait.c -o testforkexecwait $ ./testforkexecwait Tue Apr 24 19:14:32 EDT 2018 Tue Apr 24 19:14:35 EDT 2018 Tue Apr 24 19:14:38 EDT 2018 Tue Apr 24 19:14:41 EDT 2018 Tue Apr 24 19:14:44 EDT 2018 Tue Apr 24 19:14:47 EDT 2018 Tue Apr 24 19:14:50 EDT 2018 Tue Apr 24 19:14:53 EDT 2018 Tue Apr 24 19:14:56 EDT 2018 ^C */