用C语言实现简单的shell程序,包括cd,clr,dir,echo,environ,help,pause,quit指令
时间: 2023-05-25 08:06:56 浏览: 138
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/wait.h>
void cd(char **args);
void clr();
void dir();
void echo(char **args);
void environ();
void help();
void pause_();
void quit();
char *builtin_cmds[] = {
"cd",
"clr",
"dir",
"echo",
"environ",
"help",
"pause",
"quit"
};
void (*builtin_funcs[]) (char **) = {
&cd,
&clr,
&dir,
&echo,
&environ,
&help,
&pause_,
&quit
};
int num_builtin_cmds() {
return sizeof(builtin_cmds) / sizeof(char *);
}
int main() {
char *cmd_line, *cmd;
char **args;
int exit_code = 0;
while (1) {
printf("> ");
cmd_line = NULL;
size_t line_len = 0;
getline(&cmd_line, &line_len, stdin);
if (strcmp(cmd_line, "\n") == 0) {
free(cmd_line);
continue;
}
int arg_idx = 0;
args = malloc(sizeof(char*) * (arg_idx+1));
cmd = strtok(cmd_line, " \n");
while (cmd) {
args[arg_idx++] = cmd;
args = realloc(args, sizeof(char*) * (arg_idx+1));
cmd = strtok(NULL, " \n");
}
args[arg_idx] = NULL;
for (int i = 0; i < num_builtin_cmds(); i++) {
if (strcmp(args[0], builtin_cmds[i]) == 0) {
builtin_funcs[i](args);
break;
}
}
free(args);
free(cmd_line);
if (exit_code) {
exit(exit_code);
}
}
return 0;
}
void cd(char **args) {
if (args[1] == NULL) {
fprintf(stderr, "cd: expected argument to \"cd\"\n");
} else {
if (chdir(args[1]) != 0) {
perror("cd");
}
}
}
void clr() {
printf("\033[2J\033[1;1H"); // ANSI escape code for clearing screen
}
void dir() {
system("ls");
}
void echo(char **args) {
for (int i = 1; args[i]; i++) {
printf("%s ", args[i]);
}
printf("\n"); // end with newline
}
extern char **environ;
void environ() {
for (int i = 0; environ[i]; i++) {
printf("%s\n", environ[i]);
}
}
void help() {
printf("Type one of the following commands:\n");
for (int i = 0; i < num_builtin_cmds(); i++) {
printf("- %s\n", builtin_cmds[i]);
}
}
void pause_() {
printf("Press ENTER to continue...\n");
getchar();
}
void quit() {
exit(0);
}
```
注:为了方便,我将 `pause` 改名为 `pause_`,因为 `pause()` 是一个 POSIX 标准函数。
阅读全文