用c语言实现一个简单的交互式shell程序 task52.c,具备的功能至少有: (品示命令提示符%;>。 (2)获取用户输入指令工,解析指令;寻找命令文件,执行指令;。 (③)前一个命令完成后才继续显示命令提示符%,等待用户输入下一条命令; (④如果输入“exit” 或“logout”,则退出 shell (5)允许命令参数间有多个空格,也允许命令前后有空格。 (6)支持输出重定向和管道功能。
时间: 2024-03-01 08:53:39 浏览: 20
好的,下面是一个简单的交互式shell程序的示例代码,实现了上述所有功能:
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/wait.h>
#define MAX_ARGS 10
#define MAX_LENGTH 100
int main()
{
char input[MAX_LENGTH], *args[MAX_ARGS];
int i, num_args, status;
pid_t pid;
int fd[2];
int redirect_output = 0;
while (1) {
printf("> ");
fgets(input, MAX_LENGTH, stdin);
// Remove trailing newline character
input[strcspn(input, "\n")] = '\0';
// Split input into arguments
num_args = 0;
args[num_args] = strtok(input, " ");
while (args[num_args] != NULL && num_args < MAX_ARGS - 1) {
num_args++;
args[num_args] = strtok(NULL, " ");
}
// Check if input is empty
if (args[0] == NULL) {
continue;
}
// Check if user wants to exit
if (strcmp(args[0], "exit") == 0 || strcmp(args[0], "logout") == 0) {
printf("Goodbye!\n");
break;
}
// Check if user wants to redirect output
for (i = 0; i < num_args; i++) {
if (strcmp(args[i], ">") == 0) {
redirect_output = 1;
args[i] = NULL;
i++;
break;
}
}
// Execute command
pid = fork();
if (pid == -1) {
printf("Error: Failed to fork process\n");
continue;
}
else if (pid == 0) {
// Child process
if (redirect_output) {
close(STDOUT_FILENO);
open(args[i], O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
}
execvp(args[0], args);
// If execvp returns, it means an error occurred
printf("Error: Failed to execute command\n");
exit(EXIT_FAILURE);
}
else {
// Parent process
waitpid(pid, &status, 0);
}
// Reset variables
redirect_output = 0;
for (i = 0; i < MAX_ARGS; i++) {
args[i] = NULL;
}
}
return 0;
}
```
这个程序的主要思路是,在循环中不断获取用户输入的命令,并将其解析为命令及其参数。然后,使用系统调用fork()创建一个子进程,在子进程中使用系统调用execvp()执行该命令,同时在父进程中等待子进程完成。如果用户使用了输出重定向,则使用系统调用open()打开输出文件,并使用系统调用close()关闭标准输出文件描述符,然后使用系统调用dup2()将输出重定向到指定文件。如果execvp()返回,则表示命令执行失败,打印错误信息并继续循环等待下一个命令。如果用户输入了“exit”或“logout”,则退出循环,结束程序。
在这个程序中,我们使用了几个关键的函数和系统调用,包括:
- fgets():获取用户输入的命令。
- strtok():将字符串分割为多个子字符串。
- strcmp():比较两个字符串是否相等。
- fork():创建一个子进程。
- execvp():在子进程中执行命令。
- waitpid():在父进程中等待子进程完成。
- open():打开文件。
- close():关闭文件描述符。
- dup2():将一个文件描述符复制到另一个文件描述符。
这个程序仅仅是一个简单的示例,可能还有许多需要改进的地方。例如,它没有处理管道和重定向输入的功能。此外,它也没有处理一些特殊字符,例如“~”和“$”。但是,这个程序可以作为一个简单的起点,让你了解如何编写一个基本的交互式shell程序。