/*------------------------------------------------------------------*/ /* testforkloop.c */ /* Author: Bob Dondero */ /* Context switching among concurrent processes. */ /*------------------------------------------------------------------*/ #include #include #include #include int main(int argc, char *argv[]) { pid_t iPid; int i = 0; 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. */ for (i = 0; i < 1000; i++) printf("Parent process (%d): %d\n", (int)getpid(), i); return 0; } /*------------------------------------------------------------------*/ /* Sample execution: $ gcc -Wall -ansi -pedantic testforkloop.c -o testforkloop $ testforkloop Parent process (27915) Child process (27916): 0 Child process (27916): 1 Child process (27916): 2 ... Child process (27916): 486 Child process (27916): 487 Child process (27916): 488 Parent process (27915): 0 Parent process (27915): 1 Parent process (27915): 2 ... Parent process (27915): 997 Parent process (27915): 998 Parent process (27915): 999 Child process (27916): 489 Child process (27916): 490 Child process (27916): 491 ... Child process (27916): 997 Child process (27916): 998 Child process (27916): 999 */