-
Notifications
You must be signed in to change notification settings - Fork 0
/
commands.c
61 lines (54 loc) · 1.12 KB
/
commands.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
#include <pwd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/wait.h>
#include <unistd.h>
#include "commands.h"
int builtin_cd(char** args){
if(args[1]==NULL){
struct passwd* pw = getpwuid(geteuid());
args[1] = pw->pw_dir;
}
if(chdir(args[1]) == -1){
perror("cd");
}
else{
setenv("PWD",getcwd(NULL,0),1);
}
return 0;
}
int builtin_exit(char** arg){
return 1;
}
void runprogramm(char** args){
pid_t pid = fork();
if(pid==-1){
printf("Creating a new process failed %s",args[0]);
}
else if(pid==0){
if(execvp(args[0],args)==-1){
perror("That shouldn't happen");
}
}
else{
int status;
do{
waitpid(pid, &status, WUNTRACED);
}
while(!WIFEXITED(status)||WIFSIGNALED(status));
}
}
int execute(char** command){
char* builtins[] = {"cd","exit"};
int builtincnt = sizeof(builtins)/sizeof(char*);
int (*builtinfunc[])(char**) = {&builtin_cd, &builtin_exit};
int i;
for(i=0;i<builtincnt;++i){
if(!strcmp(command[0],builtins[i])){
return (*builtinfunc[i])(command);
}
}
runprogramm(command);
return 0;
}