Skip to content

Instantly share code, notes, and snippets.

@nikanos
Created December 4, 2022 21:30
Show Gist options
  • Save nikanos/4b4483458dd903c2b8110f26da116448 to your computer and use it in GitHub Desktop.
Save nikanos/4b4483458dd903c2b8110f26da116448 to your computer and use it in GitHub Desktop.
linux C++ shell example using fork()
#include <iostream>
#include <string>
#include <cstring>
#include <sstream>
#include <vector>
#include <algorithm>
#include <unistd.h>
#include <sys/wait.h>
#include <signal.h>
using namespace std;
int main()
{
signal(SIGINT, SIG_IGN);
while (true)
{
string ln, str;
pid_t pid;
cout << ">";
getline(cin, ln);
istringstream is(ln);
vector<string> vc;
while (is >> str)
vc.push_back(str);
if (vc.empty()) continue;
if (vc[0] == "quit") break;
if (vc[0] == "cd")
{
const char *path;
if (vc.size() > 1)
path = vc[1].c_str();
else
path = getenv("HOME");
if (chdir(path) < 0)
perror("chdir()");
continue;
}
pid = fork();
if (pid < 0)
{
cerr << "fork() error" << endl;
continue;
}
if (pid > 0)
{
int status;
waitpid(-1, &status, 0);
}
else
{
signal(SIGINT, SIG_DFL);
char **argv;
argv = new char*[vc.size() + 1];
for (int i = 0; i < vc.size(); i++)
{
argv[i] = new char[vc[i].length() + 1];
strcpy(argv[i], vc[i].c_str());
}
argv[vc.size()] = NULL;
execvp(vc[0].c_str(), argv);
perror("execvp()");
for (int i = 0; i < vc.size(); i++)
delete[] argv[i];
delete[] argv;
exit(0);
}
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment