Question

i am trying to write a simple ls command so i'm input "ls r" and i want to check if my code is allright. the output does not showing anything. this is the code:

int main(void){

  char *line;
  char *args[16];
  pid_t pid; 

    line = (char*)malloc(1024);
    printf("$ "); 
    fgets(line,1024,stdin);
     args[0] = strtok(line, " ");
     args[1] = strtok(NULL, " "); 

    printf("%s\n" , args[0]);
    printf("%s", args[1]);

    execvp(args[0], args);
}

thanks all.

Was it helpful?

Solution

Look inside the source code of existing free software shells (i.e. sash or bash) and read Advanced Linux Programming

Read execvp(3) man page. Notice that execvp can fail. When it succeeds, it does not return! Also, stdout(3) is buffered, you need to call fflush(3).

You are probably missing some basic understanding (a shell is forking processes, read also fork(2) & execve(2) etc...)

Try first:

int main(void){
 char line[1024];
 char *args[16];
 memset (args, 0, sizeof(args));
 printf("$ ");
 fflush(NULL); 
 fgets(line,sizeof(line),stdin);
 args[0] = strtok(line, " ");
 args[1] = strtok(NULL, " "); 
 printf("%s\n" , args[0]);
 printf("%s", args[1]);
 fflush(NULL);
 execvp(args[0], args);
 perror("execvp");
 return EXIT_FAILURE;
}

Don't forget the relevant #include directives needed by fflush(3), fgets, execvp, perror.

Read also errno(3), syscalls(2)...

Compile using gcc -Wall -g. Learn how to use the debugger gdb and also strace

BTW, real shells don't use strtok(3); they parse the line explicitly (and they have to, since a shell can escape a space with a backslash or a quote).

Actually, try strace ls; you'll find out that /bin/ls uses stat(2).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top