This is a piece of code found on Internet
#include
#include
int main(int argc, char* argv[])
{
putenv("PATH=/nothinghere");
//setenv("PATH","/nothinghere");
system(argv[1]);
return 0;
}
if I do
$./a.out "ls"
sh: 1: ls: not found
Of course
But what if
$./a.out "echo $PATH"
/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games
It print the original $PATH
!!
If we create a new shell then do the samethings
int main(int argc, char* argv[])
{
putenv("PATH=/nothinghere");
//setenv("PATH","/nothinghere");
system("/bin/sh");
return 0;
}
$./a.out
$ echo $PATH
/nothinghere
$ ls
/bin/sh: 2: ls: not found
Why?
Is it kind of problem about fork
or the implementation of echo
?
Answer
This is because you're using double quotes, telling your shell to replace $PATH
with the value of the PATH variable before it even starts a.out
.
The wrong value is thus being inserted not by the shell invoked by system()
, but by the shell you're interactively typing commands at.
To fix it, change:
$ ./a.out "echo $PATH"
to:
$ ./a.out 'echo $PATH'
No comments:
Post a Comment