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
execlp
correctly.execlp
takes 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
v
variants 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
j
in your loop where you are usingstrtok
. Also note that forexecvp
the last element of the array should beNULL
so 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 theexec
functions. Ifexec
returned that means there was an error, otherwise it never returns.errno
is set whenexec
fails so you can check that. For completeness find, sections of corrected code below with comments:And where you call
exec
Let me explain he comment at
execvp
in greater detail. Theexec
variants with ap
in their name take a filename instead of a path. These variants will mimic how a shell works and use thePATH
environment variable to look for the binary. Therefore if you do something likeexeclp("ls", "ls", "-l", NULL);
it will work assuming you havels
in 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.