だから私はシェル用にこのコードを持っています:
#include <stdio.h>
#include <stdlib.h>
#define MAX_NUM_ARGS 256
#define SIZE 256
void orders(char *command[SIZE]);
int main() {
char buffer[SIZE]= "";
//char input_args[MAX_NUM_ARGS];
char **input_args = NULL;
int i = 0;// counting variable
int blah = 0;
printf("Welcome to the AY shell.\n");
while(1){
//initialize array of strings
//first free any prevously allocated memory
if (input_args != NULL)
{ //memory has been allocated free it
for (i = 0; i <MAX_NUM_ARGS; i++)
{
free(input_args[i]);
}
}
//free array of strings
free(input_args);
//new allocate memory
input_args = (char**) malloc(sizeof(char*) * MAX_NUM_ARGS);
//check return value for error
if (input_args == NULL)
{
printf("We are out of memory. =(\n");
continue;
//print error: out of memory, exit with a error code
exit(0);
}
//allocate memory for each string
for (i = 0; i <MAX_NUM_ARGS; i++)
{
input_args[i]= (char*)malloc(sizeof(char) * MAX_NUM_ARGS);
if(input_args[i] == NULL)
{//error
printf("Error, the input is empty.");
continue;
}//end of if statement
}//end of for loop
printf("~$: "); //prompts the user for input
fgets(buffer, sizeof(buffer), stdin);
//if the user types in exit, quit
if (strcmp(buffer, "exit\n") == 0){
exit(0);
} //end of if statement
//if user types in clear, wipe the screen and repeat the lop
else if(strcmp(buffer, "clear\n")==0){
system("clear");
continue;
}//end of else if
//should the user punch in nothing, repeat the loop
else if (strcmp(buffer, "\n") == 0) {
continue;
}//end of else if
input_args[1] = NULL;
for (i = 0; i < SIZE; i++) {
if(buffer[i] != '\n' && buffer[i] != ' ' && buffer[i] != '\t'){
input_args[0][i] = buffer[i];
} //end of if statement
else{
input_args[0][i] = '\0';
}//end of else statment
}//end of for loop
//if the input doesn't fall under the conditionals above, execute orders.
orders(input_args);
} //end of while loop
return 0;
}//end of main function
void orders(char *command[SIZE]){
//handles the commands of the shell
int retval = 0; //return value
int pid = 0;
int childValue = 0;
pid = fork();
if (pid != 0){
// printf("I'm the parent, waiting on the child.\n");//debug
pid = waitpid(-1, &childValue,0);
// printf("Child %d returned a value of %x in hex.\n", pid, childValue);
return;//return backs to the main prompt
}//end of if statement
else{
// printf("I am the first child.\n");
retval = execvp(command[0], command);
exit(2);
if (retval != -1){
//print error!
printf("Invalid command!\n");
exit(2);
}
}//end of else block
}//end of orders function
これで、ls や pwd などの clear、exit、および 1 語のコマンドを適切に実行できるようになりました。ただし、「vim」などの複数行のコマンドは機能せず、ディレクトリも変更されません。
私は何を間違っていますか?
retval = execvp(command[0], command); を疑っています。問題を引き起こしていますが、完全にはわかりません。何かご意見は?これは宿題であり、正しい方向へのプッシュにすぎないため、直接的な回答は必要ありません。