小编Ter*_*ini的帖子

system()中的echo $ PATH给出了错误的输出

这是在Internet上找到的一段代码

#include <stdio.h>                                                                                                                                     
#include <string.h>


int main(int argc, char* argv[])
{
    putenv("PATH=/nothinghere");
    //setenv("PATH","/nothinghere");
    system(argv[1]);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

如果我做

$./a.out "ls"
sh: 1: ls: not found
Run Code Online (Sandbox Code Playgroud)

当然但是如果

$./a.out "echo $PATH"
/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games
Run Code Online (Sandbox Code Playgroud)

它打印原始$PATH!!

如果我们创建一个新shell,那么就做同样的事情

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
Run Code Online (Sandbox Code Playgroud)

为什么?是关于fork还是实施的问题echo

c linux shell

4
推荐指数
1
解决办法
90
查看次数

标签 统计

c ×1

linux ×1

shell ×1