/* This program illustrates the use of fork() to run an external command. */ #include #include #include #include #include int main() { /* Create our external sleep command. */ char* args[3] = {"sleep", "5", 0}; /* Create a child process for the sleep command. */ pid_t pid = fork(); /* If it failed, exit program. */ if (pid < 0) { fprintf(stderr, "\nFailed to fork!\n"); return 0; } /* Child process executes the sleep command. Note the exit() command in case of failure. For your shell, if you don't include this, you could leave multiple instances running. */ if (pid == 0) { printf("The child is running the command \"sleep 5\".\n"); execv("/bi/sleep", args); fprintf(stderr, "\nsleep failed!\n"); exit(EXIT_FAILURE); } /* Parent process waits for the child to terminate. */ printf("The parent is waiting for the child to terminate.\n"); waitpid(pid, NULL, 0); printf("The child has terminated.\n"); return 0; }