/*--------------------------------------------------------------------*/ /* 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 Wed Apr 24 21:26:13 EDT 2019 Wed Apr 24 21:26:16 EDT 2019 Wed Apr 24 21:26:19 EDT 2019 Wed Apr 24 21:26:22 EDT 2019 Wed Apr 24 21:26:25 EDT 2019 Wed Apr 24 21:26:28 EDT 2019 Wed Apr 24 21:26:31 EDT 2019 Wed Apr 24 21:26:34 EDT 2019 ^C */