I'm trying to create ls command. First, the code is not working if I enter "ls", it's working only when I enter the full path. Second, it's not looping after the exevcp(). why? Thanks.
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<unistd.h>
int main(void){
char *line;
char *args[32];
memset(args, 0, sizeof(args));
while (1){
line = (char*)malloc(1024);
printf("$ ");
fgets(line,1024,stdin);
args[0] = strtok(line, " ");
args[1] = strtok(NULL, " ");
execvp(args[0], args);
perror("execvp");
}
}
It's not looping since execve()
never returns. Also, this seems to be a very strange way to implement ls
: you should try to open a directory and read its contents (the list of files), not run another command, I would expect.
Look into the opendir()
and readdir()
functions, that's one way of actually implementing ls
.
And, also, please don't cast the return value of malloc()
in C.