Luna/apps/sh.cpp

111 lines
2.2 KiB
C++
Raw Normal View History

2023-03-29 15:56:56 +00:00
#include <luna/Vector.h>
2023-04-08 10:09:43 +00:00
#include <os/ArgumentParser.h>
2023-03-29 15:56:56 +00:00
2023-03-23 21:19:54 +00:00
#include <errno.h>
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
2023-03-23 21:42:24 +00:00
#include <sys/wait.h>
2023-03-23 21:19:54 +00:00
#include <unistd.h>
2023-03-29 15:56:56 +00:00
static Result<Vector<char*>> split_command_into_argv(const char* cmd)
2023-03-23 21:19:54 +00:00
{
char* str = strdup(cmd);
2023-03-29 15:56:56 +00:00
Vector<char*> result;
2023-03-23 21:19:54 +00:00
char* segment = strtok(str, " \n");
2023-03-29 15:56:56 +00:00
TRY(result.try_append(segment));
2023-03-23 21:19:54 +00:00
2023-03-29 15:56:56 +00:00
if (segment == NULL) return result;
2023-03-23 21:19:54 +00:00
for (;;)
{
segment = strtok(NULL, " \n");
2023-03-29 15:56:56 +00:00
TRY(result.try_append(segment));
2023-03-23 21:19:54 +00:00
2023-03-29 15:56:56 +00:00
if (segment == NULL) return result;
2023-03-23 21:19:54 +00:00
}
2023-03-29 15:56:56 +00:00
return result;
2023-03-23 21:19:54 +00:00
}
2023-04-08 10:09:43 +00:00
[[noreturn]] static void execute_command(const char* command)
2023-03-23 21:19:54 +00:00
{
2023-04-08 10:09:43 +00:00
Vector<char*> argv;
bool ok = split_command_into_argv(command).try_move_value_or_error(argv, errno);
if (!ok)
{
perror("failed to parse command");
exit(1);
}
if (argv[0] == NULL) exit(0);
execvp(argv[0], argv.data());
perror(argv[0]);
exit(1);
}
2023-04-13 15:04:59 +00:00
Result<int> luna_main(int argc, char** argv)
2023-04-08 10:09:43 +00:00
{
StringView file;
StringView command;
FILE* f;
os::ArgumentParser parser;
parser.add_positional_argument(file, "file"_sv, "-"_sv);
parser.add_value_argument(command, 'c', "command"_sv, true);
parser.parse(argc, argv);
if (!command.is_empty()) { execute_command(command.chars()); }
if (file == "-") f = stdin;
else
{
f = fopen(file.chars(), "r");
if (!f)
{
perror("fopen");
return 1;
}
}
2023-03-23 21:19:54 +00:00
while (1)
{
if (file == "-")
{
char* cwd = getcwd(NULL, 0);
if (!cwd)
{
perror("getcwd");
return 1;
}
printf("sh %s%c ", cwd, getuid() == 0 ? '#' : '$');
free(cwd);
}
2023-03-23 21:19:54 +00:00
2023-04-08 10:09:43 +00:00
char cmd[4096];
char* rc = fgets(cmd, sizeof(cmd), f);
if (!rc) return 0;
2023-03-23 21:19:54 +00:00
2023-04-08 10:09:43 +00:00
if (strspn(cmd, " \n") == strlen(cmd)) continue;
2023-03-24 19:53:53 +00:00
2023-03-23 21:19:54 +00:00
pid_t child = fork();
if (child < 0)
{
perror("fork");
return 1;
}
2023-03-23 21:19:54 +00:00
2023-04-08 10:09:43 +00:00
if (child == 0) { execute_command(cmd); }
2023-03-23 21:19:54 +00:00
if (waitpid(child, NULL, 0) < 0)
{
perror("waitpid");
return 1;
}
2023-03-23 21:19:54 +00:00
}
}