从 C 代码 system() 函数执行的 Linux 命令与从终端执行时给出的结果不同

Linux command executed from C code system() function giving different result as compared to when executed from Terminal

本文关键字:执行 终端 结果 Linux 代码 system 函数 命令      更新时间:2023-10-16

我正在使用system()函数从我的C代码运行一堆Linux命令。从 C 代码运行这些命令的结果与从终端运行这些命令时的结果不同。例:

std::string name("\pot ");
std::stringstream extractInfoCmd;
extractInfoCmd<<"find . -name "*.info" | xargs grep -E "^PART|^"<<name.c_str()<<"" >> information.rpt";
std::string extractInfoCmdStr = extractInfoCmd.str();
printf("n##DEBUG Command: %sn", extractInfoCmdStr.c_str());
system(extractInfoCmdStr.c_str());

如果我的输入文件包含以下 2 行:

PART: 6
pot : f

现在,如果我从终端执行相同的命令(从上面的调试日志接收),我得到了两行。但是如果我从 C system() 函数执行相同的命令,我只得到第一行,而不是第二行:

PART: 6

我一直在调试它很长时间,它的原因对我来说并不惊人。

name字符串

中的反斜杠由编译器解释,然后使用该字符串构建extractInfoCmd字符串,然后将其传递给 shell ( /bin/sh ),后者尝试再次解释它们。因此,传递给grep进程的实际字符串不是您想要的字符串。

解决此问题的最佳方法可能是避免使用system,而是使用类似 execlp 的东西,您可以在其中单独传递每个参数。

也不需要使用管道将信息从find传递到grep,您可以使用find本身来做到这一点:

find . -name '*.info' -exec grep -E '^PART|^\pot ' {} ;

或者,直接在 C 中:

execlp(
    "/usr/bin/find",
    ".",
    "-name",
    "*.info",
    "-exec",
    "grep",
    "-E",
    "^PART|^\\pot\ ",
    "{}",
    ";",
    NULL);
与其使用 shell 将输出管道传输到

文件,不如在流程中使用pipe直接将管道传输到 find 的标准输出,然后可以从中读取。