-
Notifications
You must be signed in to change notification settings - Fork 0
/
builtins.c
118 lines (112 loc) · 2.39 KB
/
builtins.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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
#include <glob.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <wordexp.h>
#include <assert.h>
#include <signal.h>
#include <wait.h>
#include "command.h"
#include "executor.h"
#include "builtins.h"
#include "aliases.h"
#include "prompt.h"
void expand_path(char **arg)
{
glob_t globbuf;
glob(*arg, GLOB_TILDE|GLOB_NOCHECK, NULL, &globbuf);
*arg = strdup(globbuf.gl_pathv[0]);
globfree(&globbuf);
}
int is_builtin(Command *c)
{
char *cmd = c->argv[0];
if (strcmp(cmd, "cd") == 0
|| strcmp(cmd, "exit") == 0
|| strcmp(cmd, "alias") == 0
|| strcmp(cmd, "fg") == 0
|| strcmp(cmd, "if") == 0)
return 1;
if (c->argc > 1 && strcmp(c->argv[1], "=") == 0)
return 1;
return 0;
}
void handle_builtins(Command *c)
{
if (strcmp(c->argv[0], "exit") == 0)
{
int exit_code = 0;
if (c->argc > 1)
{
exit_code = atoi(c->argv[1]);
}
exit(exit_code);
}
if (strcmp(c->argv[0], "cd") == 0)
{
char *path;
if (c->argc == 1)
{
path = "~";
}
else if (c->argc == 2)
{
path = c->argv[1];
}
else
{
printf("cd: Too many arguments\n");
return;
}
expand_path(&path);
int status = chdir(path);
if (status == -1)
{
printf("cd: %s: %s\n", strerror(errno), path);
}
free(path);
return;
}
if (strcmp(c->argv[0], "fg") == 0)
{
signal_process(SIGCONT);
int status;
waitpid(get_pid(), &status, 0);
return;
}
if (strcmp(c->argv[0], "alias") == 0)
{
if (c->argc == 1)
{
print_aliases();
return;
}
if (c->argc < 4)
{
fprintf(stderr, "alias: Syntax error.\n");
return;
}
add_alias(c->argv[1], c->argv[3]);
return;
}
if (strcmp(c->argv[0], "if") == 0)
{
run(c->condition);
if (get_exit_code() == 0)
{
run(c->cond_cmd);
}
}
if (c->argc > 1 && strcmp(c->argv[1], "=") == 0)
{
if (c->argc < 3)
{
fprintf(stderr, "Syntax error.\n");
return;
}
setenv(c->argv[0], c->argv[2], 1);
return;
}
}