Skip to content

Commit

Permalink
feat: a simple fork-exec pattern
Browse files Browse the repository at this point in the history
  • Loading branch information
shejialuo authored and jialuoshe committed Jan 4, 2024
1 parent 7e129ba commit 4e2b1c5
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 2 deletions.
25 changes: 24 additions & 1 deletion command/command.cpp
Original file line number Diff line number Diff line change
@@ -1,10 +1,33 @@
#include "command.hpp"

#include <iostream>
#include <stdlib.h>
#include <sys/wait.h>
#include <unistd.h>
#include <vector>

void Variable::execute() {}

void Command::execute() {}
void Command::execute() {
pid_t pid = fork();
if (pid == -1) {
std::cout << "[fork error]: cannot fork\n";
exit(EXIT_FAILURE);
} else if (pid == 0) {
std::vector<char *> argv{};
argv.resize(arguments.size() + 2);

argv[0] = const_cast<char *>(command.c_str());
for (size_t i = 0; i < arguments.size(); i++) {
argv[i + 1] = const_cast<char *>(arguments[i].c_str());
}

argv.back() = nullptr;

execv(command.c_str(), argv.data());
} else {
wait(NULL);
}
}

void PipeCommand::execute() {}
6 changes: 5 additions & 1 deletion miniShell.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -17,14 +17,18 @@ void start(std::istream &is, bool isFile = false) {
std::string script{};
std::getline(is, script);

if (script.empty()) {
if (is.eof()) {
return;
}

if (!script.empty() && script.back() == '\n') {
script.erase(script.length() - 1);
}

if (script.empty()) {
continue;
}

auto command = parser.parseScript(script);
if (command != nullptr) {
command->execute();
Expand Down

0 comments on commit 4e2b1c5

Please sign in to comment.