欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 房产 > 家装 > 【Linux C】简单bash设计

【Linux C】简单bash设计

2025/5/6 23:56:37 来源:https://blog.csdn.net/YZJincsdn/article/details/147199704  浏览:    关键词:【Linux C】简单bash设计

主要功能

    循环提示用户输入命令(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; // 处理EOF}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;
}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词