主要功能
循环提示用户输入命令(minibash$)。
创建子进程(fork())执行命令(execlp)。
父进程等待子进程结束(waitpid)。
关键问题
参数处理缺失:scanf("%s", buf) 遇到空格会截断输入,无法执行带参数的命令(如 ls -l)。
execlp 调用错误:execlp(buf, 0) 的参数列表不正确,导致命令参数未传递。正确形式应为 execlp(buf, buf, (char *)NULL)。
缓冲区溢出风险:未限制输入长度,可能导致 buf 溢出。
无退出机制:用户无法通过命令退出程序,只能强制终止。
执行流程
父进程读取输入 → 创建子进程 → 子进程执行命令 → 父进程等待 → 循环继续。
Code
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
int main() {
char buf[1024];
pid_t pid;
while (1) {
printf("minibash$ ");
if (fgets(buf, sizeof(buf), stdin) == NULL) {
break;
}
buf[strcspn(buf, "\n")] = '\0';
if (strcmp(buf, "exit") == 0) {
break;
}
pid = fork();
if (pid == 0) {
char *args[64];
int i = 0;
args[i] = strtok(buf, " ");
while (args[i] != NULL && i < 63) {
args[++i] = strtok(NULL, " ");
}
args[i] = NULL;
execvp(args[0], args);
perror("execvp error");
exit(1);
} else if (pid > 0) {
int status;
waitpid(pid, &status, 0);
if (WIFEXITED(status)) {
printf("Child exited with status %d\n", WEXITSTATUS(status));
}
} else {
perror("fork error");
}
}
return 0;
}