/* This program illustrates the use of fork() to run an external command in the background. */ #include #include #include #include #include int main() { pid_t id; pid_t pid; char seconds[5]; while (1) { printf("Sleep for how many seconds? "); scanf("%s", seconds); /* Create our external sleep command. */ char* argv[3] = {"sleep", seconds, 0}; /* Create a child process for the sleep command. */ pid = fork(); /* If it failed, exit program. */ if (pid < 0) { fprintf(stderr, "\nFailed to fork!\n"); return 0; } /* Child process executes the sleep command. */ if (pid == 0) { printf("The child is running the command \"sleep %s\".\n", seconds); execv("/bin/sleep", argv); fprintf(stderr, "\nsleep failed!\n"); exit(EXIT_FAILURE); } /* Parent process still uses waitpid(), but doesn't use a blocking wait. So, think of it as a periodic check on each loop iteration. If id > 0, we know a child has finished, so print a statement. */ do { id = waitpid(-1, NULL, WNOHANG); if (id > 0) printf("The child with ID %d has terminated.\n", id); } while (id > 0); } return 0; }