/* exectest.c Started by Jeff Ondich on 3/26/96 Last modified 16 February 2022 Modified by Tanya Amert for Fall 2023 This program gives a simple example of exec, and how a parent process can wait for a child process to return. Documentation for exec* calls: https://linux.die.net/man/3/exec. */ #include #include #include #include // A simple demonstration of fork() + execlp() + wait(). int main(int argc, char *argv[]) { pid_t pid = fork(); if (pid == 0) { /* Child */ printf("Process %d is about to execute a program\n", getpid()); fflush(stdout); // Choose one of these, and comment the other out: execlp("getanumber", "getanumber", (char *)0); // execlp("ls", "ls", "-l", (char *)0); // Check for errors (https://cplusplus.com/reference/cstdio/perror) perror("exec failed"); fflush(stdout); } else { /* Parent */ printf("Parent just created child, ID %d\n", pid); fflush(stdout); // Wait for the child to finish execution int status; pid = wait(&status); printf("My child ID %d just exited with status %d\n", pid, WEXITSTATUS(status)); fflush(stdout); } return 0; }