Luna/apps/sh.cpp
apio 0eab03848c
All checks were successful
continuous-integration/drone/push Build is passing
sh: Remove unused include
2023-04-07 15:41:37 +02:00

75 lines
1.5 KiB
C++

#include <luna/Vector.h>
#include <errno.h>
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/wait.h>
#include <unistd.h>
static Result<Vector<char*>> split_command_into_argv(const char* cmd)
{
char* str = strdup(cmd);
Vector<char*> result;
char* segment = strtok(str, " \n");
TRY(result.try_append(segment));
if (segment == NULL) return result;
for (;;)
{
segment = strtok(NULL, " \n");
TRY(result.try_append(segment));
if (segment == NULL) return result;
}
return result;
}
int main()
{
while (1)
{
fputs("sh$ ", stdout);
char command[4096];
char* rc = fgets(command, sizeof(command), stdin);
if (!rc) return 0;
if (strspn(command, " \n") == strlen(command)) continue;
pid_t child = fork();
if (child < 0)
{
perror("fork");
return 1;
}
if (child == 0)
{
Vector<char*> argv;
bool ok = split_command_into_argv(command).try_move_value_or_error(argv, errno);
if (!ok)
{
perror("failed to parse command");
return 1;
}
if (argv[0] == NULL) return 0;
execvp(argv[0], argv.data());
perror(argv[0]);
return 1;
}
if (waitpid(child, NULL, 0) < 0)
{
perror("waitpid");
return 1;
}
}
}