Created
September 7, 2018 02:13
-
-
Save AlecTaylor/ff5ba6a7e2a7da32c33c0a9fde5f314d to your computer and use it in GitHub Desktop.
This file contains hidden or 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
#include <string> | |
// #include <vector> | |
#include <unistd.h> | |
void execute(const char*, const char*); | |
int main(int argc, char *argv[]) { | |
if (argv[1] == NULL || argv[2] == NULL) { | |
printf("Usage %s PATH 'cmd0 ; cmd1 ; ...\n", argv[0]); | |
exit(2); | |
} | |
const std::string delim = ";", s = argv[2]; | |
unsigned start = 0U; | |
size_t end = s.find(delim); | |
// std::vector<std::string> tokens; | |
if (end == std::string::npos) { | |
execute(argv[1], s.c_str()); | |
// tokens.push_back(s); | |
} | |
else while (end != std::string::npos) { | |
execute(argv[1], s.substr(start, end - start).c_str()); | |
// tokens.push_back(s.substr(start, end - start)); | |
start = end + delim.length(); | |
end = s.find(delim, start); | |
} | |
printf("%s\n", s.substr(start, end).c_str()); | |
} | |
void execute(const char* path, const char* command) { | |
printf("execute(%s) with PATH: %s\n", command, path); | |
const pid_t i = fork(); | |
printf("i = %d\n", i); | |
if (i > -1) { | |
char* p = strdup(path); | |
const int ret = execl(strcat(p, strcat("/", command)), "-1", (char *)0); | |
free(p); | |
_exit(ret); | |
} else { | |
perror("fork failed"); | |
_exit(3); | |
} | |
} |
This file contains hidden or 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
$ g++ -std=c++11 -Wno-writable-strings cmd_runner.cc -o cmd_runner && ./cmd_runner /bin ls | |
execute(ls) with PATH: /bin | |
i = 11202 | |
i = 0 | |
Bus error: 10 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment