【发布时间】:2013-11-18 16:15:40
【问题描述】:
我有一个任务要求我编写一个 mini-shell——它会得到一个命令来执行,执行它,然后等待更多的命令。
当我将命令ls . 传递给这个迷你shell 时,它会打印当前目录的比赛。当我传递给它ls 它什么也不打印。为什么?
这是我的代码:
#include <stdio.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <string.h>
#include <unistd.h>
#include <assert.h>
#include <stdlib.h>
#include <stdbool.h>
#define MAX_CMD_SIZE 40
char** parse(char*);//will parse the arguments for the execv/excevp commands.
int main(int argc, char** argv)
{
bool debug = false;
assert(argc <= 2);
if (argc == 2)
{
//check for string -debug
debug = true;
}
if (debug)
printf("INFO: Father started PID[%d]\n", getpid());
char *command = malloc(MAX_CMD_SIZE);
while(true)
{
printf("minishell> ");
fgets(command, MAX_CMD_SIZE, stdin);
if (strcmp(command, "exit\n") == 0)
return 0;
pid_t pid = fork();
assert(pid >= 0);
if (pid == 0) //child
{
if (debug)
printf("INFO: Child started PID[%d]\n", getpid());
char** buf = parse(command);
if (debug)
{
int i;
for (i = 0; buf[i]; i++)
printf("INFO: buf[%d] = %s\n",i,buf[i]);
}
execvp(buf[0],buf);
return 0;
}
else //father
{
int status;
wait(&status);
if (debug)
printf("INFO: Child with PID[%d]terminated, continue waiting commands\n", pid);
}
}
}
char** parse(char *string)
{
char** ret = malloc(sizeof(char*));
ret[0] = strtok(string, " ");
int i = 0;
for (; ret[i]; ret[i] = strtok(NULL, " \n"))
{
ret = realloc(ret, sizeof(char*) * ++i);
}
return ret;
}
【问题讨论】:
-
你的解析函数:O,错误肯定来自这里,做一个“字符串到Word选项卡”功能,以后会更容易。
-
@Gabson 我也这么认为,但我找不到错误。
-
尝试运行带有多个参数的命令;你会看到只有第一个被传递给
execvp。 -
@chepner 没有。它不会发生。试过了。
-
对于
debug,ls foo bar应该只在buf中显示ls和foo。