strtok and execlp in a mini-shell
Question
I'm writing a mini-shell to get more familiar with Unix process management in C. It's reading stuff from commandline and passes these arguments via execlp to the system.
# include <stdio.h>
# include <stdlib.h>
# include <unistd.h>
#define MAXSIZE 100
char prompt[MAXSIZE];
int main(void)
{
pid_t pid;
printf("> ");
// read stuff
if (fgets(prompt, MAXSIZE, stdin) == NULL){
printf("Input validation error!");
abort();
}
// printf("DEBUG: %s" , prompt);
if (strcmp(prompt, "exit")==0) abort();
if ((pid=fork())<0){ // copy process
printf("Process error!");
abort();
}
if (pid==0){ // exec in son-prcess
char *command=(char*)strtok(prompt, " ");
execlp(command, command, 0); // overwrite memory
printf("Error, command not found!");
abort();
} else {
waitpid(pid, 0, 0);
}
}
In fact this would be it, but I don't get any output from execlp()
.
Does anybody know why that is?
Solution
I tried running your program and it failed because command
contained a \n
(newline). I altered it by putting \n
instead of " " in the strtok
and it then ran successfully.
In detail:
if (pid==0){ // exec in son-prcess
char *command=(char*)strtok(prompt, "\n");
printf ("'%s'\n", command);
execlp (command, command, 0); // overwrite memory
printf("Error %d (%s)\n", errno, strerror (errno));
abort();
} else {
Test run:
$ ./a.out > ls 'ls' (usual ls behaviour)
OTHER TIPS
Kinopiko already found why it doesn't work, but the reason you didn't see any error message is that your shell prompt is overwriting it. Try putting a newline at the end:
printf("Error, command not found!\n");
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow