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

Ter*_*ini 4 c linux shell

这是在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

Cha*_*ffy 11

这是因为你使用双引号,告诉你的shell 在它开始之前$PATH用PATH变量的值替换.a.out

因此,错误的值不是由shell调用的system(),而是由shell以交互方式键入命令.

要修复它,请更改:

$ ./a.out "echo $PATH"
Run Code Online (Sandbox Code Playgroud)

至:

$ ./a.out 'echo $PATH'
Run Code Online (Sandbox Code Playgroud)