質問

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.

他のヒント

It's not looping because (to quote the man page):

The exec family of functions replaces the current process image with a new process image.

In other words, execvp() only returns if there's been an error.

While we're on the subject, you might want to read up on fork-exec.

I am not sure about the path issue; execvp() is certainly supposed to search $PATH (and does when I test your code on my computer, so ls and /bin/ls work equally well).

One thing to bear in mind is that fgets() returns the terminating newline, which ends up in your args array. If, for example, you enter ls with no arguments and press enter, args[0] will be set to ls\n', and execvp() will fail.

Oh, and you have a memory leak since you never free line.

Here is a simple way to implement ls command using c. To run use for example ./xls /tmp

    #include<stdio.h>
    #include <dirent.h>
    void main(int argc,char *argv[])
    {
   DIR *dir;
   struct dirent *dent;
   dir = opendir(argv[1]);   

   if(dir!=NULL)
      {
   while((dent=readdir(dir))!=NULL)
                    {
        if((strcmp(dent->d_name,".")==0 || strcmp(dent->d_name,"..")==0 || (*dent->d_name) == '.' ))
            {
            }
       else
              {
        printf(dent->d_name);
        printf("\n");
              }
                    }
       }
       close(dir);
     }
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top