c++ - 如何在 C++ 中将字符串作为 shell 脚本执行?

标签 c++

我正在编写一个需要能够执行用户提供的 shell 脚本的程序。我已经得到它来执行单个 shell 命令,但提供的脚本会比这更复杂。

Google 搜索到以下代码片段:

FILE *pipe;
char str[100];

// The python line here is just an example, this is *not* about executing
// this particular line.
pipe = popen("python -c \"print 5 * 6\" 2>&1", "r");

fgets(str, 100, pipe);
cout << "Output: " << str << endl;

pclose(pipe)

所以这个点str里面有30。到目前为止,一切都很好。但是,如果命令中有回车符,就像 shell 脚本文件一样,如下所示:

pipe = popen("python -c \"print 5 * 6\"\nbc <<< 5 + 6 2>&1", "r");

我的目标是 str 最终有 30\n11

换句话说,假设我有一个包含以下内容的文件:

python -c "print 5 * 6"
bc <<< 5 + 6

我发送给上面的 popen 的参数是该文件的字符串表示形式。我想从 C++ 中将该字符串(或类似的东西)发送到 bash 并让它完全执行,就好像我在 shell 中并使用 获取它一样。 file.sh,但将 str 变量设置为我在 shell 中看到的值(如果它在那里执行),在本例中为 30\n11

是的,我可以将其写入文件并以这种方式工作,但这似乎是不必要的。

我不认为这是一个新问题,所以要么我以完全错误的方式思考它,要么有一个我根本不知道的库已经在做这件事。

最佳答案

使用 bash -c

#include <stdio.h>

int main()
{
    FILE *pipe = popen("bash -c \"echo asdf\necho 1234\" ", "r");
    char ch;
    while ((ch = fgetc(pipe)) != EOF)
        putchar(ch);
}

输出:

asdf
1234

(我在cygwin上测试过)

关于c++ - 如何在 C++ 中将字符串作为 shell 脚本执行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25090468/

相关文章:

c++ - 聚合对象是否强制成为 IUnknown 引用?

c++ - 程序结束后内存泄漏有影响吗?

c++ - 使用 hash_map<vector<int>,string> 失败,为什么?

c++ - Qt (C++) 日志充满 "Widget (address) does not have a property named (var)"

c++ - 理解返回 void 的 CAF actor 函数

c++ - OpenMP 优化 for 循环的调度

c++ - 两步到一步初始化和错误处理

C++ : Covariant return type without pointer

c++ - .NET 从具有 www 接口(interface)的打印机获取数据

c++ - "transform(s.begin(), s.end(), s.begin(), tolower)"Xcode 5无法编译