Написание интерпретатора или больше как программа командной строки
Я должен написать программу-интерпретатор, которая больше похожа на командную строку. Это некоторая справочная информация:
General flow of basic interpreter
1. Prompt for user request.
2. Carry out the user request.
3. Unless user terminates the program, go to step 1.
Run a command. Format:
R command_path [arg1 to arg4]
//a single character ‘R’ which stands for 'Run', followed by the path of the command
//the user can supply up to 4 command line arguments
Behavior:
a. If command exist, run the command in a child process with the supplied
command line arguments
Wait until the child process is done
b. Else print error message “XXXX not found”, where XXXX is the user
entered command
Например.
YWIMC > R /bin/ls
a.out ex2.c ...... //output from the “ls” command
YWIMC > R /bin/ls –l //same as executing “ls –l”
total 144
-rwx------ 1 sooyj compsc 8548 Aug 13 12:06 a.out
-rwx------ 1 sooyj compsc 6388 Aug 13 11:36 alarmClock
.................... //other files not shown
Идея, которую я имею до сих пор, заключается в том, чтобы прочитать путь к файлу, прочитать аргументы, использовать execv (filePath, args). Тем не менее, я не могу получить правильный цикл и синтаксис.
while(scanf("%s", args[i]) !=0) { //read in arguments
i++;
}
execv(filePath,args);
это читает бесконечное количество аргументов. как я сказал, я не могу понять синтаксис правильно. обработка строк в C такая боль :(
Re отредактированы. Это мой текущий код, который является довольно неполным
#include <stdio.h>
#include <fcntl.h> //For stat()
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h> //for fork(), wait()
int main()
{
char request, filePath[100];
int result, pathExist, childID, status;
struct stat buf;
//read user input
printf("YWIMC > ");
scanf("%c", &request);
while (request != 'Q'){ //if 'Q' then just exit program
// Handle 'R' request
scanf("%s", &filePath); //Read the filePath/program name
pathExist = stat(filePath, &buf);
if(pathExist < 0) {
printf("%s not found\n", filePath);
}
else {
result = fork();
if(result != 0) { //Parent Code
childID = wait(&status);
}
else { //Child Code
if(strcmp(filePath, "/bin/ls") == 0) {
execl("/bin/ls", "ls", NULL); //change to execv
} //with the use of a 2D
//string array
else { //same for this
execl(filePath, NULL);
}
return 256;
}
}
fflush(stdin); //remove all left over inputs
printf("YWIMC > ");
scanf("%c", &request);
}
printf("Goodbye!\n");
return 0;
}