/*-------------------------------------------------------------------*/ /* 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 (29242) Child process (29243): 0 Child process (29243): 1 Child process (29243): 2 ... Child process (29243): 460 Parent process (29242): 0 Child process (29243): 461 Parent process (29242): 1 Child process (29243): 462 Parent process (29242): 2 Child process (29243): 463 Parent process (29242): 3 Child process (29243): 464 Parent process (29242): 4 Child process (29243): 465 ... */