przykladowe-projekty/Microshell

82 lines
2.0 KiB
Plaintext

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#define MAXARGS 256
int main()
{
char* usrinput = NULL;
int n = 0;
while (1)
{
char pwd[100];
getcwd(pwd,100);
printf("[%s] &",pwd);
char readcomm = getline(&usrinput, &n, stdin);
if (usrinput[readcomm-1] == '\n')
{
usrinput[readcomm-1] = 0;
}
char* command[MAXARGS + 1] = {strtok(usrinput, " "), 0 };
char* ptr;
int i = 1;
while (ptr = strtok(NULL, " "))
{
command[i] = ptr;
i++;
}
if (strcmp(command[0], "exit")==0)
{
return 0;
}
if (strcmp(command[0], "help")==0)
{
printf("\n========================================\n= Arkadiusz Charliński =\n");
printf("= własna implemantacja: exit, help, cd =\n========================================\n\n");
continue;
exit(EXIT_FAILURE);
}
if (strcmp(command[0],"cd") == 0)
{
if (command[1]==NULL)
{
chdir(getenv("HOME"));
continue;
exit(EXIT_FAILURE);
}
else
{
chdir(command[1]);
continue;
exit(EXIT_FAILURE);
}
}
int pid = fork();
if (pid==0 && strcmp(command[0],"help") !=0 && strcmp(command[0],"cd") !=0 && strcmp(command[0],"exit") !=0)
{
execvp(command[0], command);
perror(command[0]);
exit(EXIT_FAILURE);
}
else
{
waitpid(pid, NULL, 0);
}
}
return 0;
}