quit command and verbosity
[minishell-2.git] / Sources / opsys.cpp
blob8c80c7d73c71c6c11bfcb28c615a4335a48488f5
1 #include "Headers/opsys.h"
3 OpSys OS; // Global OpSys variable. Should be accessible to all modules.
4 bool exit_program = false;
6 void signal_handler(int s)
8 if (s==SIGINT)
10 cout << "\nSIGINT (Ctrl+C) received. Code " << s << ". Exiting.\n";
11 exit_program = true; // We'll do this instead of an exit(0) in order to allow for cleanup.
14 if (s==SIGHUP)
16 cout << "\nSIGHUP received. Code " << s << ". Exiting.\n";
17 exit_program = true; // We'll do this instead of an exit(0) in order to allow for cleanup.
21 SignalHandler::SignalHandler()
23 signal_action.sa_handler = signal_handler;
24 sigemptyset(&signal_action.sa_mask);
25 signal_action.sa_flags = 0;
26 sigaction(SIGINT, &signal_action, NULL);
29 string OpSys::get_cwd()
31 char temp[MAXPATHLEN];
32 return getcwd(temp, sizeof(temp)) ? std::string( temp ) : std::string("");
35 void OpSys::change_dir(vector<string> command)
37 string cmd = "";
38 for(unsigned short int i = 1; i < command.size(); i++)
40 cmd += command[i];
42 if (chdir(cmd.c_str()))
44 cerr << "miniShell: cd: " << cmd << ": Arquivo ou diretório não encontrado\n";
46 else {
47 get_cwd();
48 cwd_changed = true;
52 vector<const char*> make_argv(vector<string>const& in)
54 vector<const char*> out;
55 out.reserve(in.size() + 1);
56 for (const auto& s : in)
57 out.push_back(s.data());
58 out.push_back(nullptr);
59 out.shrink_to_fit();
60 return out;
63 short OpSys::simple_command(vector<string> tokens)
65 int status;
66 if(is_verbose)
68 cerr << "execvp(\"" << tokens[0] << "\",\"";
69 for(unsigned int i = 0; i < tokens.size()-1; i++)
70 cerr << tokens[i] << ' ';
71 cerr << tokens.back();
72 cerr << "\");\n";
76 pid_t pid = fork();
77 if (pid == 0)
79 //printf("execlp(%s, %s, NULL);", bincmd.c_str(), command.c_str());
80 execvp(tokens[0].c_str(), const_cast<char* const *>(make_argv(tokens).data()));
81 cerr << tokens[0] << ": command not found.\n";
82 return 0; // TODO: exit with cleanup
84 else if (pid < 0)
86 printf("Couldn't fork a process.");
87 return 0;
89 waitpid(-1, &status, WUNTRACED);
90 return 1;
93 OpSys::OpSys()
95 cwd = get_cwd();
96 if(cwd.empty())
97 cerr << RED_ANSI << "Could not get the current working directory.\n" << RESET_ANSI;
99 uid_t uid = geteuid(); // Gets the effective ID of the user that started miniSHELL
100 struct passwd pwent;
101 struct passwd *pwent_ptr;
102 char buffer[1024];
104 // Looks for the UDI on the password databank and saves the result on pwent
105 getpwuid_r(uid, &pwent, buffer, sizeof buffer, &pwent_ptr);
106 username = pwent.pw_name; // Saves username
108 char hostname[64];
109 gethostname(hostname, 64);
110 this->hostname = hostname;