从 C 代码 system() 函数执行的 Linux 命令与从终端执行时给出的结果不同
Linux command executed from C code system() function giving different result as compared to when executed from Terminal
我正在使用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
的标准输出,然后可以从中读取。
相关文章:
- 在执行其他功能的同时播放动画(LED矩阵和Arduino/ESP8266)
- C++,系统无法执行指定的程序
- 在终端中运行可执行文件与在Mac查找器中打开
- 从 GUI 文件资源管理器执行程序,并且不生成终端
- QProcess无法通过QPushButton执行终端线路命令
- 如何在调试模式下通过终端运行可执行的 c++?
- 即使可执行文件的输入是从文件重定向的,如何强制从终端输入?
- 使用 QT 创建器通过树莓派上的 Wifi 执行简单的终端命令
- 从 C 代码 system() 函数执行的 Linux 命令与从终端执行时给出的结果不同
- 通过C编程打开终端并执行命令
- 如何在linux上的新终端上执行新线程
- 如何在gnome终端中执行CLion程序
- 您如何在通过终端执行程序时获取用户输入器
- 如果命令不只是打印结果,而是进入某种交互模式,如何处理来自C++的终端命令执行的输出?
- 创建命令并通过linux终端执行
- linux mint终端不执行Qt creator给出的命令
- 在一个执行函数中使用多个终端命令
- 如何使用c++/python程序在终端中运行程序,然后在该程序中执行语句
- 在终端上执行"make"时出错
- C++代码仅在程序从终端运行时执行