用c语言写一个简单的Unix Shell
时间: 2023-11-20 15:05:24 浏览: 36
好的,下面是一个简单的Unix Shell的C语言实现,包括读取用户输入,解析命令行参数,执行命令等基本功能:
```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
int main()
{
char* command;
char* arguments[MAX_NUM_ARGUMENTS];
char input_buffer[MAX_COMMAND_LENGTH];
int should_run = 1;
while (should_run)
{
// Print prompt string
printf("osh> ");
// Read user input
fgets(input_buffer, MAX_COMMAND_LENGTH, stdin);
// Replace newline character with null terminator
input_buffer[strlen(input_buffer) - 1] = '\0';
// Parse command line arguments
int arg_count = 0;
command = strtok(input_buffer, " ");
while (command != NULL && arg_count < MAX_NUM_ARGUMENTS - 1)
{
arguments[arg_count++] = command;
command = strtok(NULL, " ");
}
arguments[arg_count] = NULL;
// Exit shell if user enters "exit" command
if (strcmp(arguments[0], "exit") == 0)
{
should_run = 0;
}
else
{
// Fork child process to execute command
pid_t pid = fork();
if (pid == 0) // Child process
{
execvp(arguments[0], arguments);
exit(0);
}
else if (pid > 0) // Parent process
{
wait(NULL);
}
else // Fork error
{
printf("Fork failed\n");
}
}
}
return 0;
}
```
这个简单的Shell程序只支持输入一个命令,不支持管道、重定向等高级特性。但是它可以作为一个基础框架,用于实现更复杂的功能。