I create an array of strings to put attributes to the command (e.g. ls -l), but exec command wants an array of chars, how can i resolve it? this code should create a child which execute a command chosen by input.. I have even some problems with the wait() when pid != 0.. Can you help me out to finish it? Thank you a lot.
int main(void) {
char array[100];
char character;
int i = 0;
char* point;
int j = 0;
printf ("Digit a string");
printf ("\n");
do {
character = getchar();
array[i] = character;
i++;
}
while (character != '\n');
array[i-1] = '\0';
i = 0;
char* string[100];
char *word = strtok(array, " .");
while (word != NULL) {
printf("%s\n", word);
string[j] = word;
word = strtok(NULL, " .");
}
printf ("\n");
pid_t pid;
pid = fork();
if (pid == -1) {
perror("");
}else if (pid == 0) {
if (execlp(string, NULL) < 0) { /* execute the command */
exit(1);
}
else {
//.. wait until the child ends
wait(pid);
}
}
return;
}
Your big issue is you are not using
execlpcorrectly.execlptakes a variable number of arguments that are the arguments passed to the program. It is expected to work like this:What you have is an array of arguments so you want to use one of the
vvariants of exec. You can find all the variants here. So what you want to do is something more like this:Note that the command itself is one of the arguments as in both examples. Another issue with your program is you are not incrementing
jin your loop where you are usingstrtok. Also note that forexecvpthe last element of the array should beNULLso exec knows what it has found the last argument. One final thing is that you do not have to check the return value of any of theexecfunctions. Ifexecreturned that means there was an error, otherwise it never returns.errnois set whenexecfails so you can check that. For completeness find, sections of corrected code below with comments:And where you call
execLet me explain he comment at
execvpin greater detail. Theexecvariants with apin their name take a filename instead of a path. These variants will mimic how a shell works and use thePATHenvironment variable to look for the binary. Therefore if you do something likeexeclp("ls", "ls", "-l", NULL);it will work assuming you havelsin one of the folders specified byPATH. If you doexecl("ls", "ls", "-l", NULL);(not the lack of ap) it will fail as"ls"is not a valid path; it would have to be something like"/usr/bin/ls"instead. Which version you want, something that takes a filename or a file path, depends on your application.