-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbuiltins.c
More file actions
93 lines (84 loc) · 2.11 KB
/
Copy pathbuiltins.c
File metadata and controls
93 lines (84 loc) · 2.11 KB
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
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
// Function Declarations for builtin shell commands:
int lsh_cd(char **args);
int lsh_help(char **args);
int lsh_exit(char **args);
/*
List of builtin commands, followed by their corresponding functions.
Since this is global, it can be accessed from anywhere.
*/
char *builtin_str[] = {
"cd",
"help",
"exit"
};
/*
List of function pointers, which prevents using if statements multiple times.
The parameter must be aligned, because we call one of the functions like (*builtin_func[i])(args);
*/
int (*builtin_func[]) (char**) = {
&lsh_cd,
&lsh_help,
&lsh_exit
};
/**
* @brief This function gets the number of built-in functions.
*
* @return int the number of built-in functions.
*/
int lsh_num_builtins() {
return sizeof(builtin_str) / sizeof(char *);
}
/**
* @brief This function is the implementation of the command 'cd'.
*
* @param args the command 'cd' and a path.
* @return int status code.
*/
int lsh_cd(char **args)
{
if (args[1] == NULL) {
fprintf(stderr, "lsh: expected argument to \"cd\"\n");
} else {
// use chdir function to change the current directory.
if (chdir(args[1]) != 0) {
perror("lsh");
}
}
return 1;
}
/**
* @brief This function is the implementation of the command 'help'.
*
* @param args arguments.
* @return int status code.
*/
int lsh_help(char **args)
{
(void)args;
printf("Yushiro Murakami's LSH\n");
printf("Type program names and arguments, and hit enter.\n");
printf("The following are built in:\n");
for (int i = 0; i < lsh_num_builtins(); i++) {
printf(" %s\n", builtin_str[i]);
}
printf("Use the man command for information on other programs.\n");
return 1;
}
/**
* @brief This function is the implementation of the command 'exit'.
*
* @param args arguments.
* @return int status code.
*/
int lsh_exit(char **args)
{
(void)args;
// By setting the status code 0, the lsh_loop function can escape from while loop.
return 0;
}