#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/wait.h>
#define BUFFER 64
char *read_command(void);
char **parse_line(char *line);
int execute(char **arguments);
int main(void)
{
char *command = NULL;
char **arguments;
int status;
do
{
printf("protoulis_7968> ");
command = read_command();
arguments = parse_line(command);
status = execute(arguments);
free(arguments);
free(command);
}while(status);
}
char *read_command(void)
{
char *command = NULL;
ssize_t buf = 0;
getline(&command, &buf, stdin);
return command;
}
char **parse_line(char *line)
{
int buffer = BUFFER;
int pos = 0;
char **tokens = malloc(buffer * sizeof(char*));
char *token;
if (!tokens)
{
printf("Error allocating memory with malloc\n");
exit(0);
}
token = strtok(line, " \t\r\n\a");
while(token != NULL)
{
tokens[pos] = token;
pos++;
if (pos >= buffer)
{
buffer += BUFFER;
tokens = realloc(tokens, buffer * sizeof(char*));
if (!tokens)
{
printf("Error reallocating memory!\n");
exit(0);
}
}
token = strtok(NULL, " \t\r\n\a");
}
tokens[pos] = NULL;
return tokens;
}
int execute(char **arguments)
{
// printf("%*c\n", arguments);
int pid, waitPid, status;
pid = fork();
if(pid == 0) //child process
{
if (execvp(arguments[0], arguments) == -1)
perror("Error with EXECVP\n");
}
else if (pid < 0)
perror("Error PID < 0\n");
else //parent process
{
do
{
waitPid = waitpid(pid, &status, WUNTRACED);
}while(!WIFEXITED(status) && !WIFSIGNALED(status));
}
return 1;
}
好吧,我已经用 C 编写了上面的代码来模拟命令行解释器。我希望能够通过在一行中输入它们来执行多个命令。我的意思是我想作为输入传递例如行: ls -l ;触摸 hello.c ;密码。通过这一整行后,我想用分号分隔命令,让系统以任何顺序执行每个命令。我相信我必须使用 strtok 函数,但已经做了很多尝试但什么也没做。非常感谢任何帮助!
最佳答案
strtok
在您的情况下是不够的。原因是它会将您带到下一个子命令,但要能够执行此子命令,您必须将其作为单个字符串。
解决这个问题的两种方法:
- 数一数有多少';'有,用'\0'代替,内存中有几个连续的字符串,然后一个一个执行。
- 编写一个函数,将您的命令字符串拆分为一个二维子命令数组,然后一个一个地执行它们。
如果您需要一些灵感,可以使用以下代码:
关于c - 在 C 中实现命令行解释器,特殊情况,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43681859/