【发布时间】:2020-04-10 20:55:52
【问题描述】:
我正在尝试读取由分号分隔且前后有空格的命令行参数(例如 ls ; date ; cal),但分隔部分一直很困难。当我简单地输入一个单独的命令行(例如ls 或date)时,我的代码可以工作,但是每当我输入分号时,它就不起作用(例如ls ; date)
这是我的 C 代码:
void parse(char *userInput, char **splitInput)
{
//read until userInput is not end of line
while (*userInput != '\0')
{
//replace any space in userInput as '\0'
while (*userInput == ';')
{
*userInput++ = '\0';
}
//save the argument position
*splitInput++ = userInput;
//if userinput is not equal to space, read next userInput
while (*userInput != ' ' && *userInput != ';' && *userInput != '\0')
{
userInput++;
}
}
}
void execute(char **splitInput)
{
pid_t pid = fork();
if (pid > 0) //parent process
{
pid_t parent_pid;
parent_pid = wait(NULL);
}
else if (pid == 0) //child process
{
if (execvp(*splitInput, splitInput) < 0)
{
printf("%s: command not found\n", *splitInput);
exit(1);
}
}
else //error
{
perror("fort error");
}
}
void main(void)
{
char userInput[100]; //execvp's first argument
char *splitInput[100]; //execvp's second argument
while(strcmp(userInput,"quit") != 0)
{
//ask for a user input
printf("group 10> ");
//read the entire line of input
scanf("%[^\n]", userInput);
//get characters from input; stop the loop problem
getchar();
//quit if user input is equal to quit
if (strcmp(userInput, "quit") == 0)
{
exit(0);
}
//parse the input
parse(userInput, splitInput);
//execute fork
execute(splitInput);
}
}
【问题讨论】:
-
使用
strtok()将输入拆分为一个字符。 -
请注意,“它不起作用”从不足以说明问题。始终陈述预期的(期望的)行为和观察到的行为,并最好指出它们之间的差异。可能您的问题是 shell 解析命令行,如上面 Jörg Beyer 所述。如果不是显示你的程序做了什么和你想让程序做什么。
-
@JörgBeyer:程序不通过
main中的argc和argv机制接受参数。你认为shell解析涉及到哪里? -
splitInput未按照execvp的要求以空指针终止。 -
暂时关闭
execvp和可能使用 cmets 或#if语句的fork调用。在很多地方添加printf语句来告诉你程序正在做什么:它找到了哪些字符串,如果它正在调用它会传递给execvp,等等。熟悉您的程序的实际行为方式。
标签: c command-line separator