/*--------------------------------------------------------------------*/ /* testforkwait.c */ /* Author: Bob Dondero */ /* The fork and wait system calls. */ /*--------------------------------------------------------------------*/ #include #include #include #include #include int main(int argc, char *argv[]) { pid_t iPid; int i = 0; int iStatus; printf("Parent process (%d)\n", (int)getpid()); 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. */ for (i = 0; i < 1000; i++) printf("Child process (%d): %d\n", (int)getpid(), i); exit(0); } /* This code is executed by only the parent process. */ /* Wait for the child process to terminate. */ iPid = wait(&iStatus); if (iPid == -1) {perror(argv[0]); exit(EXIT_FAILURE); } printf("Child process terminated with status %d.\n", WEXITSTATUS(iStatus)); for (i = 0; i < 1000; i++) printf("Parent process (%d): %d\n", (int)getpid(), i); return 0; } /*--------------------------------------------------------------------*/ /* Sample execution: $ gcc217 testforkwait.c -o testforkwait $ testforkwait Parent process (25752) Child process (25753): 0 Child process (25753): 1 Child process (25753): 2 ... Child process (25753): 997 Child process (25753): 998 Child process (25753): 999 Child process terminated with status 0. Parent process (25752): 0 Parent process (25752): 1 Parent process (25752): 2 ... Parent process (25752): 997 Parent process (25752): 998 Parent process (25752): 999 */