1.验证
- 输入
cd /path/to/directory
以切换目录。 - 输入
ls
以列出当前目录内容。 - 输入
pwd
以显示当前工作目录。 - 输入
exit
以退出程序。
2.代码实现结果:
3.源码解析:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/wait.h>
#define MAX_INPUT_SIZE 1024
#define MAX_ARGS 64
// 解析命令行输入
int parse_input(char *input, char **args) {
int i = 0;
char *token = strtok(input, " \t\n");
while (token != NULL && i < MAX_ARGS - 1) {
args[i] = token;
token = strtok(NULL, " \t\n");
i++;
}
args[i] = NULL;
return i;
}
// 执行外部命令
void execute_external_command(char **args) {
pid_t pid = fork();
if (pid == 0) {
// 子进程
if (execvp(args[0], args) == -1) {
perror("execvp");
exit(EXIT_FAILURE);
}
} else if (pid > 0) {
// 父进程
wait(NULL);
} else {
perror("fork");
}
}
// 处理cd命令
void handle_cd(char **args) {
if (args[1] == NULL) {
fprintf(stderr, "Expected argument to 'cd'\n");
} else {
if (chdir(args[1]) != 0) {
perror("chdir");
}
}
}
int main(int argc, const char *argv[])
{
char input[MAX_INPUT_SIZE];
char *args[MAX_ARGS];
while (1) {
printf("myshell> ");
if (fgets(input, MAX_INPUT_SIZE, stdin) == NULL) {
break;
}
// 解析输入
parse_input(input, args);
// 检查是否是内置命令
if (strcmp(args[0], "cd") == 0) {
handle_cd(args);
} else if (strcmp(args[0], "exit") == 0) {
break;
} else {
// 执行外部命令
execute_external_command(args);
}
}
return 0;
}