Created
February 7, 2018 15:26
-
-
Save jhunt/7d670a77aabeaf684bad66e6a8675e2e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* for execvpe(...): */ | |
#define _GNU_SOURCE | |
#include <stdio.h> | |
#include <string.h> | |
#include <unistd.h> | |
#include <errno.h> | |
#include <sys/types.h> | |
#include <sys/wait.h> | |
int main(int argc, char **argv) { | |
int rc, i; | |
char **cmd, **envp; | |
envp = argv+1; | |
cmd = NULL; | |
for (i = 1; i < argc; i++) { | |
if (strcmp(argv[i], "--") == 0) { | |
argv[i] = NULL; | |
cmd = argv+i+1; | |
break; | |
} | |
} | |
if (!cmd || !*cmd) { | |
fprintf(stderr, "USAGE: %s ENV=VALUE -- command --to --run --with /arg/u/ments\n", argv[0]); | |
return 1; | |
} | |
fprintf(stderr, "setting up execution environment:\n"); | |
for (i = 0; envp[i]; i++) { | |
fprintf(stderr, " %s\n", envp[i]); | |
} | |
fprintf(stderr, "running command %s with arguments:\n", cmd[0]); | |
for (i = 1; cmd[i]; i++) { | |
fprintf(stderr, " [%d]: '%s'\n", i-1, cmd[i]); | |
} | |
for (;;) { | |
pid_t pid; | |
int status; | |
pid = fork(); | |
if (pid < 0) continue; | |
if (pid == 0) { | |
execvpe(cmd[0], cmd, envp); | |
continue; | |
} | |
for (;;) { | |
rc = waitpid(pid, &status, 0); | |
if (rc == -1 && errno == EINTR) continue; | |
if (rc == -1 && errno == ECHILD) break; | |
break; | |
} | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment