I am coding a basic shell and my first requirement is to test for cd, I have all my conditions for the possible cd commands, after which, I will handing commands like ls. As for now I am really confused about one block of code.
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#define MAX_TOK 50
#define MAX_LEN 100
#define BUFSIZE 81
int tokenize(char *cmd, char tokens[MAX_TOK][MAX_LEN]){
char *token;
int NUM_TOKENS = 0;
//printf("Splitting the string \"%s\" into tokens:\n",cmd);
token = strtok(cmd, " ");
while(token != NULL){
strcpy(tokens[NUM_TOKENS],token);
token = strtok(NULL, " ");
NUM_TOKENS++;
}
return NUM_TOKENS;
}
void decide(char tokens[MAX_TOK][MAX_LEN], int NUM_TOKENS){
char *home = getenv("HOME");
int success;
char *cd = {"cd"};
char *string = tokens[1];
//printf("Number of tokens %d\n", NUM_TOKENS);
//printf("%d\n",strcmp(tokens[0], cd));
if(strcmp(tokens[0], cd) == 0){
if(NUM_TOKENS > 2){
printf("error: Too many arguments\n");
}
else{
printf("Changing to new directory %s \n",tokens[1]);
char *string = tokens[0];
//printf("%s\n", tokens[1]);
success = chdir(tokens[1]);
printf("%d\n",success);
}
}
else{
printf("Completing the %s request\n",tokens[0]);
take_action(tokens[0]);
}
}
void take_action(char *cmd){
printf("%s\n",cmd);
int len;
int return_code;
char buffer[BUFSIZE];
int pid;
pid = fork();
if(pid != 0){
//parent process executing
wait(NULL);
}else{
//child process executing
len = strlen(buffer);
if(buffer[len-1] == '\n'){
buffer[len-1] = '\0';
}
return_code = execlp(cmd, cmd, NULL);
if(return_code != 0){
printf("Error executing %s.\n", cmd);
}
}//end else
}
int main(){
char *cmd;
char tokens[MAX_TOK][MAX_LEN];
int len;
int return_code;
char buffer[BUFSIZE];
int pid;
while(cmd != NULL){
printf("Enter a command\n");
cmd = fgets(buffer, BUFSIZE, stdin);
// find the command
int NUM_TOKENS = tokenize(cmd, tokens);
//print_tokens(NUM_TOKENS, tokens);
decide(tokens,NUM_TOKENS);
}
}//end main
When hardcoding chdir("test")
the code runs fine, if a user on the command line enters "cd test"
tokens[0]
is cd
and tokens[1]
is the string "test"
but chdir(tokens[1])
fails and I don't understand why.
Printing tokens[1] also shows "test" as the string stored. As well when passing a parameter to take_action I am told conflicting types occurs. In both print statements the proper string is shown. As far as I can tell there are no extra spaces because my tokentize function strips them all. I am so confused, these two parts seem so simple but just wont work.