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],"ty开发者_运维百科pe")==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);
}
}
It sounds like you're looking for the which
command:
$ which ls
/bin/ls
Are you looking for which?
which <command>
will show you where the executable is located
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.
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");
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.
精彩评论