我正在编写一个需要能够执行用户提供的 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/