tags:

views:

133

answers:

5

i am doing a project about shell, and i want the code that gives me the path the system() function uses.

example, when i enter the command

type dir

the reply will be

dir is external command (/bin/dir)

this is what i reached, but its not working

else if(strcmp(arg3[0],"type")==0) //if type command
        {
            if(strcmp(arg3[1],"cat")==0 || strcmp(arg3[1],"rm")==0 || strcmp(arg3[1],"rmdir")==0 || strcmp(arg3[1],"ls")==0 || strcmp(arg3[1],"cp")==0 ||                   strcmp(arg3[1],"mv")==0 || strcmp(arg3[1],"exit")==0 || strcmp(arg3[1],"sleep")==0 || strcmp(arg3[1],"type")==0|| strcmp(arg3[1],"history") ==0)
            {
                printf("%s is a Rshell builtin\n", arg3[1]);
            }
            else
            {
                printf("%s is an external command\n", arg3[1]); 
                char * pPath;
                pPath = getenv ("PATH");
                 if (pPath!=NULL)
                    printf ("The current path is: %s",pPath);


            }
        }
+2  A: 

It sounds like you're looking for the which command:

$ which ls
/bin/ls
Greg Hewgill
how to implemented in Cis it just like this $ which(arg[1])where arg[1] contains the command name??
charly
how to use the which in the coding??
charly
@charly: To do the same thing as the `which` command, use `getenv("PATH")`, separate the individual elements with `:`, and look for the desired command in each path element.
Greg Hewgill
man if you can look at the code above plz :D
charly
@charly: Your code above is incomplete, it doesn't split the path apart on the `:` character.
Greg Hewgill
A: 

Are you looking for which?

which <command>

will show you where the executable is located

Simon Groenewolt
A: 

If you are asking how the searching functionality of the "type" command works, it simply searches all the directories contained in the PATH environment variable until it finds the specified file (which must be executable by the user). This is quite easy to implement yourself - I don't think there is a POSIX library function that does it, but I'm no POSIX expert.

anon
A: 

Two ways:

First off note that system() will use another shell, not yours. Most implementations use the default of /bin/sh, which could be a Bourne shell or bash... you need to find out what your c runtime does. popen() almost always does the same as system() anyway this is true on Solaris, HPUX, and with glibc.

FILE *cmd=popen("/usr/bin/echo $PATH");
char tmp[256]={0x0};

if (cmd!=NULL)
{
   while (fgets(tmp, sizeof(tmp), cmd)!=NULL)   
     printf("%s", tmp);
   pclose(cmd);
}

/* or */
system("/usr/bin/echo $PATH");
jim mcnamara
A: 

You could always try downloading the open source code for whereis which is standard on most Linux distributions and read up the code and see how it is implemented.

tommieb75