/* * fork_and_wait.c * This will fork a child process. The * child process will sleep for the given * amount of secconds before exiting. * The parent process will wait for * the child to exit and then collect the * exit status. * * to compile: gcc -O -pipe fork_and_wait.c -o fork_and_wait */ #include #include #include #include #include int main(int argc, char **argv) { int amount, status; pid_t child, wait_val; /* * This first arg to main is always the * program name ! */ if(argc > 1 ) { amount = atoi(argv[1]); printf("PARENT: Spawing child\n"); child = fork(); /* Child process */ if( child == 0 ) { /* * just sleep and exit */ printf("CHILD: Sleeping for [ %d ] secconds \n", amount); sleep(amount); exit(0); } else { /* * Parent * first initiate status to 0, then call wait */ status = 0; printf("PARENT: Waiting child PID [ %d ] \n", child ); wait_val = waitpid(child, &status, 0); /* * Now check the status of the child process */ if( WIFEXITED(status) ) { printf("PARENT: Child exited normally with exit satus [ %d ]\n", WEXITSTATUS(status)); } if( WIFSIGNALED(status) ) { printf("PARENT: Child exited due to signal number [ %d ]\n", WTERMSIG(status) ); } } /* else, if (child == 0 ) */ } /* if(argc) */ /* FIN */ return(0); }