sh: add builtins
This commit is contained in:
parent
20db8eaba6
commit
a815beacfb
@ -1,6 +1,7 @@
|
||||
#include <luna.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <sys/wait.h>
|
||||
#include <unistd.h>
|
||||
|
||||
@ -9,8 +10,8 @@ static int status;
|
||||
typedef struct
|
||||
{
|
||||
char* buffer;
|
||||
long size;
|
||||
long capacity;
|
||||
size_t size;
|
||||
size_t capacity;
|
||||
} command;
|
||||
|
||||
void show_prompt()
|
||||
@ -18,6 +19,33 @@ void show_prompt()
|
||||
printf("[%ld]> ", getpid());
|
||||
}
|
||||
|
||||
int command_matches(command* cmd, const char* string)
|
||||
{
|
||||
if (cmd->size <= strlen(string)) // cmd->size includes null terminator
|
||||
return 0;
|
||||
return strncmp(cmd->buffer, string, strlen(string)) == 0;
|
||||
}
|
||||
|
||||
int command_matches_exactly(command* cmd, const char* string)
|
||||
{
|
||||
if (cmd->size <= strlen(string)) // cmd->size includes null terminator
|
||||
return 0;
|
||||
if (cmd->size > (strlen(string) + 1)) return 0;
|
||||
return strncmp(cmd->buffer, string, strlen(string)) == 0;
|
||||
}
|
||||
|
||||
int command_match_builtins(command* cmd)
|
||||
{
|
||||
if (command_matches(cmd, "exit ")) { exit(atoi(cmd->buffer + 5)); }
|
||||
if (command_matches_exactly(cmd, "exit")) { exit(0); }
|
||||
if (command_matches_exactly(cmd, "pid"))
|
||||
{
|
||||
printf("pid %ld, ppid %ld\n", getpid(), getppid());
|
||||
return 1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
void command_expand(command* cmd, long new_capacity)
|
||||
{
|
||||
char* buffer = realloc(cmd->buffer, new_capacity);
|
||||
@ -58,6 +86,12 @@ void command_clear(command* cmd)
|
||||
void command_execute(command* cmd)
|
||||
{
|
||||
command_push(cmd, '\0');
|
||||
if (command_match_builtins(cmd))
|
||||
{
|
||||
command_clear(cmd);
|
||||
show_prompt();
|
||||
return;
|
||||
}
|
||||
pid_t child = fork();
|
||||
if (child < 0)
|
||||
{
|
||||
|
Loading…
Reference in New Issue
Block a user