c - echo $PATH in system() 给我一个错误的输出

标签 c linux shell

<分区>

这是网上找的一段代码

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


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

如果我这样做

$./a.out "ls"
sh: 1: ls: not found

当然 但是如果

$./a.out "echo $PATH"
/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games

它打印原始的 $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

为什么? forkecho 的实现有问题吗?

最佳答案

这是因为您使用了双引号,告诉您的 shell 将 $PATH 替换为 PATH 变量的值 甚至在 a.out 开始之前>.

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

要修复它,更改:

$ ./a.out "echo $PATH"

到:

$ ./a.out 'echo $PATH'

关于c - echo $PATH in system() 给我一个错误的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51885161/

相关文章:

c - 如何向linux内核添加代码?

arrays - 如何将数组传递给 bash 函数

shell - Sublime Text 2 : subl shell command often fails to open files

shell - 如何使用 awk 或 sed 将每个单独出现的单词替换为其他单词?

c - 将unsigned char字节打包成c中的unsigned int

c - 如何在C中解决 "control may reach end of non-void function"?

linux - 巨大的 Oracle 重做日志

linux - tarring 时消除目录层次结构

调用传递给另一个函数的函数指针

C、打开gl,绘制直到另一行