Pliki_SOP/Microshell/microshell.c

66 lines
1.2 KiB
C
Raw Normal View History

2019-01-10 12:56:56 +01:00
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
2019-01-10 14:17:29 +01:00
#include <sys/types.h>
#include <sys/wait.h>
2019-01-10 12:56:56 +01:00
const int max = 1000;
2019-01-10 14:36:35 +01:00
int cut(char **argv, char *command){
2019-01-10 13:13:37 +01:00
int i = 0, w = 0, x = 0;
char argument[100];
while (1){
if(command[i] == 10){
argv[w] = NULL;
break;
}
else if (command[i] == 32){
i+=1;
x=0;
continue;
}
else{
while(command[i] != 32 && command[i]!=10){
argument[x]=command[i];
x+=1;
i+=1;
}
argument[x] = '\0';
argv[w]=malloc(x+1 * sizeof(char));
strcpy(argv[w], argument);
w+=1;
}
}
2019-01-10 14:36:35 +01:00
return w+1;
2019-01-10 12:56:56 +01:00
}
int main (){
2019-01-10 14:36:35 +01:00
int ile, i;
2019-01-10 13:13:37 +01:00
while (1){
2019-01-10 14:53:53 +01:00
char* argv[100];
2019-01-10 13:13:37 +01:00
char komenda[max], directory[max];
if (getcwd(directory, sizeof(directory)) == NULL){
perror("getcwd() error");
return 1;
}
printf("[%s]$ ", directory);
fgets(komenda, max, stdin);
2019-01-10 14:36:35 +01:00
ile = cut(argv, komenda);
2019-01-10 14:53:53 +01:00
printf("\n%s\n\n", argv[0]);
2019-01-10 13:59:45 +01:00
if (argv[0]==NULL)
continue;
2019-01-10 14:28:20 +01:00
else if (strcmp(argv[0], "exit") == 0)
2019-01-10 14:55:13 +01:00
exit(0);
2019-01-10 13:17:30 +01:00
else
2019-01-10 14:19:31 +01:00
if (fork() == 0)
2019-01-10 14:04:29 +01:00
execvp(argv[0], argv);
2019-01-10 14:15:12 +01:00
else
wait(NULL);
2019-01-10 14:36:35 +01:00
2019-01-10 14:51:03 +01:00
for(i=0; i<ile; i++)
free(argv[i]);
2019-01-10 13:13:37 +01:00
}
return 0;
2019-01-10 12:56:56 +01:00
}