用c语言写一个简单的shell
时间: 2023-06-12 22:08:18 浏览: 44
以下是一个简单的shell示例,可以执行基本的命令:
```c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
#include <string.h>
#define MAX_LINE 80 /* 命令行的最大长度 */
#define BUFFER_SIZE 50
int main(void) {
char *args[MAX_LINE/2 + 1]; /* 储存输入的命令 */
int should_run = 1; /* 用于判断程序是否结束 */
char buffer[BUFFER_SIZE];
pid_t pid;
int i;
while (should_run) {
printf("osh>");
fflush(stdout);
/* 读取命令行输入 */
fgets(buffer, BUFFER_SIZE, stdin);
buffer[strlen(buffer) - 1] = '\0'; /* 将换行符替换为字符串结束符 */
/* 将输入的命令解析为参数数组 */
i = 0;
args[i] = strtok(buffer, " ");
while (args[i] != NULL) {
i++;
args[i] = strtok(NULL, " ");
}
args[i] = NULL;
/* 创建子进程 */
pid = fork();
if (pid < 0) { /* 如果创建子进程失败 */
printf("Fork failed.\n");
exit(1);
}
else if (pid == 0) { /* 如果是子进程 */
if (execvp(args[0], args) == -1) { /* 执行命令 */
printf("Command not found.\n");
}
exit(0);
}
else { /* 如果是父进程 */
wait(NULL); /* 等待子进程结束 */
}
}
return 0;
}
```
该程序使用了fork()函数创建子进程,并使用execvp()函数执行命令。输入的命令以空格为分隔符解析为参数数组,并在子进程中执行。