/* Demonstrate wait and waitpid. Also specifying the process to 'collect' */ /* Start 2 children. Make sure 2nd exits last. Use waitpid to 'collect' */ /* it first (Line 28 'collects' 2nd child even though 1st terminated first*/ #include #include #include #include int main(argc,argv) int argc; // Parameters declared between header and opening { char *argv[]; {FILE *fp; pid_t isParent[2],retProcess[2]; int retVal[2]; if (isParent[0]=fork()) { // retProcess[0]=wait(&retVal[0]); fprintf(stdout,"Child %d Started! \n",isParent[0]); /* Don't need to flush. stderr is also not buffered */ } else { // 1st child fprintf(stderr,"1st child starts\n"); // return(5); _exit(5); } if (isParent[1]=fork()) { // Still the parent // wait for the 2nd child started. SDefinitely completes after 1st child retProcess[1]=waitpid(isParent[1],&retVal[1],0); retProcess[0]=wait(&retVal[0]); fprintf(stdout,"2nd Child %d Returns! pid=%d Value Returned: %d\n", isParent[1],retProcess[1],WEXITSTATUS(retVal[1])); fprintf(stdout,"Child %d Returns! pid=%d Value Returned: %d\n", isParent[0],retProcess[0],WEXITSTATUS(retVal[0])); } else { // 2nd child sleep(1); // sleep so the parent can collect it after starting 2nd child fprintf(stderr,"2nd child starts\n"); // return(50); _exit(23); } }