#include /* for errno() */ #include /* for ARG_MAX */ #include /* for signal(), SIG* */ #include /* for sprintf(), stderr, ... */ #include /* for exit() */ #include /* for strerror() */ #include /* for wait() */ #include /* for wait() */ #include /* for sleep(), fork() and execlp() */ #include "funcs.h" /* for infomsg(), errormsg() */ /* * Macros */ #define A_LONG_TIME 3600 #define CHILD_RUN_TIME 10 #define WAIT_INSTEAD_OF_SLEEP TRUE /* * Type and struct definitions */ /* * Global variables */ /* * Forward declarations */ pid_t start_child_sleep(void); /* * Functions */ int main( int argc, char *argv[]) { int wstatus; pid_t pid; /* * Initialise. */ /* * Start child. */ infomsg("parent starting one child ..."); pid = start_child_sleep(); /* * Monitor child */ infomsg("parent sees child has pid %d and waits for it ...", pid); #if WAIT_INSTEAD_OF_SLEEP pid = wait(&wstatus); #else sleep(A_LONG_TIME); #endif /* * Clean up and exit. */ infomsg("parent cleaning up and exiting ..."); return(0); } pid_t start_child_sleep( ) { pid_t pid; char buf[ARG_MAX]; if ((pid=fork()) < 0) errormsg("fork() failed: %s", strerror(errno)); else if (pid > 0) return(pid); /* * Only the child gets here */ sprintf(buf, "echo \"child running ...\";" "sleep %d;" "echo \"child exiting ...\"", CHILD_RUN_TIME); execlp("/bin/sh", "sh", "-c", buf, (char *) NULL); errormsg("exec() failed: %s", strerror(errno)); }