So basically I am writing a program that repeatedly reads lines of input from standard input, splits them up in a char **array. For each line, treat the first element as a full path to a program to be executed. Execute the program, passing the rest of the items on the line as arguments. If the line is empty, do nothing and go to the next line. Repeat until the first element is the string ”exit”.
My problems are:
- when I input "exit", the strcmp(l[0], "exit") returns 10 instead of 0. Why?
- The program got compiled but only works for odd number of arguments. For example, if I input "/bin/echo This is good", it prints "This is good" But if I input "/bin/echo This is very good", it prints "error".
Here is my code:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define BUFSIZE 10000
int space;
char** createArray(char *line) {
int len_line = strlen(line);
char **wordArray = NULL;
if(len_line > 1){
char *token = strtok(line, " ");
space = 0;
while (token) {
wordArray = realloc(wordArray, sizeof(char*)*++space);
wordArray[space-1] = token;
token = strtok(NULL, " ");
}
}
return wordArray;
}
int main(int argc, const char* argv[]) {
char line[BUFSIZE];
while (1) {
printf("%s\n", ">");
fgets(line, BUFSIZE, stdin);
char** l = createArray(line);
if (l) {
/*why instaed of zero, when l[0]
/*equals quit, strcmp() returns 10?*/
printf("%d\n", strcmp(l[0], "exit"));
if(strcmp(l[0], "exit")==10) {
exit(0);
}
else if(fork() == 0) {
execv(l[0], l);
printf("%s\n", "Error!");
}
}
}
return 1;
}