C语言33行代码简单实现Shell

Shell:引导程序框架,使用结构体和回调函数的方式可以简单的实现Shell,代码难度系数不高

以下是我自己写的一个小例子(附件为linux下编译生成的可执行文件)

代码:

#include <stdio.h>
typedef void (*back_way)(void);//函数类型
void A(void){printf("AAA\n");}//函数指针A
void B(void){printf("BBB\n");}//函数指针B


typedef struct func_
{
const char name;//命令名
back_way func;//命令函数指针
}func_t;
const func_t func_sel[]=  //匹配数组
{
{'A',A},{'a',A},
{'B',B},{'b',B},
{0,0},
};
const func_t* func_find(const char name)//匹配函数
{
int i = sizeof(func_sel)/sizeof(func_sel[0]);
int j = 0;
for(; j < i; j++)
if(func_sel[j].name == name)
return &func_sel[j];//找到就返回
return (const func_t*)0;//找不到返回0
}


int main()
{
char name = 'a';
const func_t *p = func_find(name);//匹配函数
if(p)p->func();//调用函数显示结果
return 0;
}


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是一个简单shell 的 C 语言代码实现,它可以执 shell 命令和内置命令: ```c #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <sys/wait.h> #define MAX_COMMAND_LENGTH 100 #define MAX_NUM_ARGUMENTS 10 char *builtin_commands[] = {"cd", "exit"}; void cd_command(char *directory) { if (directory == NULL) { fprintf(stderr, "cd: expected argument to \"cd\"\n"); } else { if (chdir(directory) != 0) { perror("cd"); } } } void execute_command(char **args) { pid_t pid = fork(); if (pid == 0) { // child process if (execvp(args[0], args) == -1) { perror("execute_command"); } exit(EXIT_FAILURE); } else if (pid < 0) { perror("execute_command"); } else { // parent process int status; do { waitpid(pid, &status, WUNTRACED); } while (!WIFEXITED(status) && !WIFSIGNALED(status)); } } void execute_builtin_command(char **args) { if (strcmp(args[0], "cd") == 0) { cd_command(args[1]); } else if (strcmp(args[0], "exit") == 0) { exit(EXIT_SUCCESS); } } int main() { char command[MAX_COMMAND_LENGTH]; char *args[MAX_NUM_ARGUMENTS]; while (1) { printf("> "); if (fgets(command, MAX_COMMAND_LENGTH, stdin) == NULL) { break; } int num_args = 0; args[num_args] = strtok(command, " \t\n"); while (args[num_args] != NULL && num_args < MAX_NUM_ARGUMENTS - 1) { num_args++; args[num_args] = strtok(NULL, " \t\n"); } args[num_args] = NULL; if (args[0] == NULL) { continue; } if (strcmp(args[0], "!!") == 0) { printf("error: no previous command to execute\n"); continue; } if (strcmp(args[0], "cd") == 0 || strcmp(args[0], "exit") == 0) { execute_builtin_command(args); } else { execute_command(args); } } return 0; } ``` 该 shell 可以执如下命令: - 内置命令 `cd`,用于改变当前工作目录。例如:`cd /home/user/documents` - 内置命令 `exit`,用于退出 shell。例如:`exit` - 外部命令,例如:`ls -l`,`gcc -o hello hello.c` 等。 除此之外,该 shell 还支持如下功能: - `!!` 命令,用于执上一条命令。例如:`ls -l`,`!!` - 忽略空白命令。例如,直接按回车键会被忽略。 - 支持使用空格和制表符分隔命令参数。 注意,该 shell实现仅供参考,可能存在漏洞和不足之处。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值