Pequeno Shell Unix em C++
Publicado por Fernando (última atualização em 02/03/2018)
[ Hits: 3.909 ]
Homepage: https://github.com/phoemur/
Pequeno Shell Unix em C++.
Compilação:
$ g++ -o shell shell.cpp -O3 -Wall -Wpedantic -std=c++11
// g++ -o shell shell.cpp -O3 -Wall -Wpedantic -std=c++11
#include <iostream>
#include <string>
#include <sstream>
#include <vector>
#include <sys/wait.h>
#include <unistd.h>
using namespace std;
vector<string> split_string(const string& input,
const char delimiter)
{
stringstream ss {input};
vector<string> result;
for (string buffer;
getline(ss, buffer, delimiter);)
{result.push_back(move(buffer));}
return result;
}
int launch_execute(const vector<string>& command)
{
// handle builtins
if (command.size() == 0) return 1;
else if (command[0] == "exit") return 0;
else if (command[0] == "cd") {
if (command.size() == 1 || command.size() > 2) {
cerr << "shell: expected 1 argument to \"cd\"\n";
}
else {
if (chdir(command[1].c_str()) != 0) {
perror("shell");
}
}
return 1;
}
// cast vector<string> to const char**
const char **argv = new const char* [command.size()+1];
for (unsigned j = 0; j < command.size(); ++j) {
argv [j] = command[j].c_str();
}
argv[command.size()] = NULL;
// fork
int status = 0;
pid_t pid = fork();
if (pid == 0) {
// Child process
if (execvp(argv[0], (char **)argv) == -1) {
perror("shell");
}
delete[] argv;
exit(EXIT_FAILURE);
} else if (pid < 0) {
// Error forking
perror("shell");
} else {
// Parent process
do {
waitpid(pid, &status, WUNTRACED);
} while (!WIFEXITED(status) && !WIFSIGNALED(status));
}
delete[] argv;
return 1;
}
int main()
{
int status = 0;
string line = "";
do {
cout << "shell> ";
getline(cin, line);
vector<string> args = split_string(line, ' ');
status = launch_execute(args);
} while (status);
return 0;
}
Balanceamento de parênteses utilizando Pilha
Nenhum comentário foi encontrado.
Gentoo: detectando impressoras de rede e como fixar uma impressora por IP
Como o GNOME conseguiu o feito de ser preterido por outras interfaces gráficas
Gentoo binário em 2026: UEFI, LUKS, Btrfs e Systemd
Trabalhando Nativamente com Logs no Linux
Jogando Daikatana (Steam) com Patch 1.3 via Luxtorpeda no Linux
Por que sua empresa precisa de uma PKI (e como automatizar EMISSÕES de certificados via Web API)
Instalando NoMachine no Gentoo com Systemd (acesso Remoto em LAN)
Gentoo: Trocando wpa_supplicant pelo iwd no NetworkManager (Systemd)
Vou destruir sua infância:) (6)
Quando vocês pararam de testar distros? (24)
O que houve com slackware ??? (12)









