c - 自定义 shell 无法识别传递给它的最后一个命令
问题描述
我正在尝试实现一个自定义的 Unix shell,但是,传递给它的最后一个命令永远无法识别。当我运行“ls”时,没有任何反应,但如果我执行“ls ls”,它就像只通过了一个 ls,或者如果我执行“ls -o”,它只执行“ls”,但如果我执行“ls - o -o” 它执行“ls -o”,它的功能应该类似于标准的 Unix shell。
#include "apue.h"
#include <sys/wait.h>
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
int parse(char* buf, char **cmds);
static void sig_int(int);
int
main(void)
{
char *path;
path = getenv("PATH");
char buf[MAXLINE];
char *envp[] = {path, NULL};
pid_t pid;
int status;
char *command[MAXLINE];
char *input;
if (signal(SIGINT, sig_int) == SIG_ERR)
err_sys("signal error");
printf("%% ");
while (fgets(buf, MAXLINE, stdin) != NULL) {
parse(buf, command);
if ((pid = fork()) < 0) {
err_sys("fork error");
} else if (pid == 0) { /* child */
input = command[0];
execvpe(input, command, envp);
err_ret("couldn't execute: %s", buf);
exit(127);
}
/* parent */
if ((pid = waitpid(pid, &status, 0)) < 0)
err_sys("waitpid error");
printf("%% ");
}
exit(0);
}
/*parses input into something runable*/
int parse(char* buf, char **cmds)
{
char *sep;
int count;
count = 0;
while((sep = strchr(buf, ' ')))
{
cmds[count]= buf;
*sep = '\0';
buf = sep +1;
count++;
while (*buf && (*buf == ' ')) /* Ignore spaces */
buf++;
}
cmds[count] = NULL;
if(count == 0)
return 1;
return 0;
}
解决方案
推荐阅读
- ios - iOS 奇数线程 1:致命错误:iPad 上的索引超出范围
- javascript - 如何查询溢出隐藏区域中的元素:滚动
- java - 如何提高嵌入在 pdf 中的签名图像的质量
- javascript - 仅使用 Array.prototype.map() 和 Array.prototype.filter() 来实现以下结果
- autodesk-forge - AutoDesk Forge 上的 DWG 图纸组合失败
- anaconda - 在 IBM Power 9 机器上使用 conda 安装 MKL
- javascript - 为什么 Position:Top of my table 不基于文档对象?
- django - 提交带有多个不同按钮的表单
- amazon-web-services - 发生无服务器首次部署错误:HelloLogGroup - 用户
- javascript - 使用js的倒数计时器