/*--------------------------------------------------------------------*/ /* testforkwaitpid.c */ /* Author: Iasonas Petras */ /*--------------------------------------------------------------------*/ #include #include #include #include #include /*--------------------------------------------------------------------*/ /* Demonstrate the system-level fork() and waitpid() functions. Return 0. As usual, argc is the command-line argument count, and argv contains the command-line arguments. */ int main(int argc, char *argv[]) { pid_t iPid; int iRet; int i = 0; int iStatus; printf("%d parent\n", (int)getpid()); iRet = fflush(NULL); if (iRet == EOF) {perror(argv[0]); exit(EXIT_FAILURE); } iPid = fork(); if (iPid == -1) {perror(argv[0]); exit(EXIT_FAILURE); } if (iPid == 0) { /* This code is executed by the child process only. */ for (i = 0; i < 10; i++) printf("%d child %d\n", (int)getpid(), i); exit(0); } /* This code is executed by the parent process only. */ /* Wait for the child process to terminate. */ iPid = waitpid(iPid, &iStatus, 0); if (iPid == -1) {perror(argv[0]); exit(EXIT_FAILURE); } if (WIFEXITED(iStatus)) printf("Child with process id %d exited with status=%d\n", iPid, WEXITSTATUS(iStatus)); for (i = 0; i < 10; i++) printf("%d parent %d\n", (int)getpid(), i); return 0; } /* $ gcc217 testforkwaitpid.c -o testforkwaitpid $ ./testforkwaitpid 22859 parent 22860 child 0 22860 child 1 22860 child 2 22860 child 3 22860 child 4 22860 child 5 22860 child 6 22860 child 7 22860 child 8 22860 child 9 Child with process id 22860 exited with status=0 22859 parent 0 22859 parent 1 22859 parent 2 22859 parent 3 22859 parent 4 22859 parent 5 22859 parent 6 22859 parent 7 22859 parent 8 22859 parent 9 */