/*-------------------------------------------------------------------*/ /* testforkloop.c */ /* Context switching among concurrent processes. */ /*-------------------------------------------------------------------*/ #include #include #include int main(int argc, char *argv[]) { int iPid; int i = 0; printf("Parent process (%ld)\n", (long)getpid()); fflush(NULL); iPid = fork(); if (iPid == -1) {perror(argv[0]); return 1; } if (iPid == 0) { /* This code is executed by only the child process. */ while (1) { printf("Child process (%ld): %d\n", (long)getpid(), i); i++; } exit(0); /* Should never reach. */ } while (1) { printf("Parent process (%ld): %d\n", (long)getpid(), i); i++; } return 0; /* Should never reach. */ } /* Sample execution: --> gcc -Wall -ansi -pedantic -o testforkloop testforkloop.c --> testforkloop Parent process (1276) Parent process (1276): 0 Parent process (1276): 1 ... Parent process (1276): 580 Parent process (1276): 581 Child process (1277): 0 Child process (1277): 1 ... Child process (1277): 62 Child process (1277): 63 Parent process (1276): 582 Parent process (1276): 583 ... */