c - 采用多字命令的基本 shell
问题描述
我正在尝试实现一个接受命令的外壳;但是,我无法让它正常工作。例如,如果我输入“ls -a”,我会得到:
无效选项——“”
尝试“ls --help”以获取更多信息。
作为初学者,我可能犯了一些严重的错误,所以请原谅我。另外,我会将读取命令的代码放入函数中。就像这样用于测试-谢谢。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <unistd.h>
#include <stddef.h>
int main()
{
pid_t pid;
int status;
char* token;
char* argv[20];
char input[100];
printf("AP> ");
while (1)
{
fgets(input, 100, stdin);
token = strtok(input, " ");
int i = 0;
//walk through other tokens
while (token != NULL) {
argv[i] = malloc(strlen(token) + 1);
strncpy(argv[i], token, strlen(token));
//argv[i] = token;
i++;
token = strtok(NULL, " ");
}
argv[i] = NULL; //argv ends with NULL
pid = fork();
if (pid < 0)
{
perror("fork error");
return EXIT_FAILURE;
}
else if (pid == 0)
{
// child process
execvp(argv[0], argv);
perror("execl error");
return EXIT_FAILURE;
}
else {
// parent process
if (waitpid(pid, &status, 0)<0)
{
perror("waitpid error");
return EXIT_FAILURE;
}
}
printf("AP> ");
}
return 0;
}
解决方案
input
如果您在内部 while 循环之后插入以下循环,那么您会看到您没有在 while 循环开始之前删除末尾的换行符。
for (i=0; argv[i]; i++)
printf("argv[%d] = '%s'\n", i, argv[i]);
或者,您可以使用:
" \n"
作为你的分隔符,而不仅仅是
" "
推荐阅读
- dart - 如何删除 scoped_model 状态?
- python - 为什么我不断收到 bin/sh: 1 :: not found
- python - 可以通过 MySQL Workbench 但不能通过 python 连接到 AWS RDS
- javascript - 客户端上的 encodeURIComponent 和服务器上的 decodeURIComponent
- jquery - 根据鼠标悬停时子div的属性设置父div的背景图片
- reactjs - Textarea autoheight 在 flex 中不起作用
- java - Netbeans IDE 用户 - 在 Windows 10 上安装 Netbeans 8.0.2 时出现问题
- powershell - 使用 PowerShell 刷新 Power BI
- python - 在 python 中使用内联模式读取 XML
- amazon-web-services - 将死信队列配置添加到 AWS Lambda