c++ - execlp 的多行输出

标签 c++ exec

我正在尝试使用 execlp 返回多行输出,但我不确定这样做的确切方法。我试过了

#include <iostream>
#include <string>
#include <unistd.h>
using namespace std;

int main()
{
   string str = "echo ";
   str += "one \n";
   str += "two \n";
   str += "three \n";
   if(execl("/bin/sh","/bin/sh","-c",str.c_str(),(char*)NULL) == -1)
   {
      printf("Child Execution Failed\n");
      exit(1); 
   }                
   exit(0);
   return 0;
}

我基本上希望在 shell 中打印所有 onetwothree。我得到以下输出

one
/bin/sh: 2: two: not found
/bin/sh: 3: three: not found

再次感谢!

答案:找到一个简单的答案:

#include <iostream>
#include <string>
#include <unistd.h>
using namespace std;

int main()
{
   string str = "echo one\n";
   str += "echo two\n";
   str += "echo three\n";

   if(execl("/bin/sh","/bin/sh","-c",str.c_str(),(char*)NULL) == -1)
   {
      printf("Child Execution Failed\n");
      exit(1); 
   }                
   exit(0);
   return 0;
}

最佳答案

execlp 将调用它的当前进程替换为 execlp 参数中指定的程序。查看man page并注意:

The exec() family of functions replaces the current process image with a new process image.

多次尝试调用 execlp 的循环是没有意义的,因为在第一次调用 execlp 之后,您的程序将不再执行。有一些方法可以将 execlpfork 结合使用或 fork 的变体之一)可以工作,但有更简单的选择......

相反,使用 popen运行一个不同的子进程并有一个管道来读取它的输出。

关于c++ - execlp 的多行输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48723241/

相关文章:

python - 为什么 `exec()` 不在脚本中工作而是交互工作?

c++ - boost 单元测试 mpl 列表的笛卡尔积

c++ - std::string 或 std::vector<char> 保存原始数据

PHP exec - 在进度期间逐行回显输出

c - C中的多个管道

c - 在C中获取CPU(用户和系统)和子进程的实际使用时间

C++ 从 ifstream 读取() : without pointers?

C++:无法使用 Mini-XML 从 XML 文件加载长字符串

c++ - C++ 中的动态链接不起作用

bash tee 去除颜色