Replacing the process with exec in C
exec never returns on success, because the process becomes the new program.
#include <stdio.h>
#include <sys/wait.h>
#include <unistd.h>
int run(const char *program, char *const argv[]) {
pid_t pid = fork();
if (pid < 0) {
return -1;
}
if (pid == 0) {
execvp(program, argv);
perror("execvp");
_exit(127);
}
int status = 0;
waitpid(pid, &status, 0);
return WIFEXITED(status) ? WEXITSTATUS(status) : -1;
}
int list_files(void) {
char *args[] = {"ls", "-1", NULL};
return run("ls", args);
}
How it works
- The argument list is NUL-terminated by a NULL pointer.
execvpsearches PATH;execvneeds a full path.- Any code after a successful exec is unreachable.
Keywords and builtins used here
NULLcharconstifintlist_filespid_treturnrunvoid
The run, in numbers
- Lines
- 23
- Characters to type
- 413
- Tokens
- 135
- Three-star pace
- 105 tpm
At the three-star pace of 105 tokens a minute, this run takes about 77 seconds.
Step 2 of 4 in Processes & signals, step 8 of 14 in Systems programming.