#include /* printf, etc */ #include /* almost always need this with system programming */ #include /* fork, getpid, getppid */ #include /* free, malloc, etc */ #include #include /* Another fork test program - this has the parent wait for the child to die. The child reads a string from standard input (using readline) and then exits. The parent looks at the status code from the child and prints out some stuff... */ /* this function is only called by the child */ void child() { char *s; pid_t me = getpid(); printf("%u: Child is running\n",me); printf("%u: Parent pid is %u\n",me,getppid()); s = readline("Child is waiting for a line of text: "); free(s); } /* this function is only called in the parent */ void parent(pid_t childpid) { pid_t me = getpid(); int cstat; printf("%u: Parent is running\n",me); printf("%u: Child pid is %u, waiting ...\n",me,childpid); wait(&cstat); printf("%u: wait returned.\n",childpid); /* print out some status information */ if (WIFEXITED(cstat)) printf("Child exited with status code %d\n",WEXITSTATUS(cstat)); if (WIFSIGNALED(cstat)) printf("Child was killed by signal %d\n",WTERMSIG(cstat)); if (WIFSTOPPED(cstat)) printf("Child is stopped, signal was %d\n",WSTOPSIG(cstat)); } int main(int argc, char **argv) { pid_t childpid; if (childpid = fork()) { /* fork returns child's pid in the parent - this is parent only code */ parent(childpid); } else { /* fork returned 0 - this is child only code */ child(); } return(0); }