/*------------------------------------------------------------------*/ /* 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]); return 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]); return 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: $ gcc -Wall -ansi -pedantic testforkwait.c -o testforkwait $ testforkwait Parent process (29335) Child process (29336): 0 Child process (29336): 1 Child process (29336): 2 Child process (29336): 3 ... Child process (29336): 997 Child process (29336): 998 Child process (29336): 999 Child process terminated with status 0. Parent process (29335): 0 Parent process (29335): 1 Parent process (29335): 2 Parent process (29335): 3 ... Parent process (29335): 997 Parent process (29335): 998 Parent process (29335): 999 */