我应该编写一个更像命令提示符的解释器程序。这是一些背景信息:
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 中处理字符串真是太痛苦了:(
重新编辑。这是我当前的代码,相当不完整
#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;
}