C++ - Linux/shell 脚本运行子进程并获取它们的返回状态

标签 c++ linux bash process execute

我正在寻找一种解决方案,以便在 Linux 上用 C++ 编写一段程序,该程序解析包含具有一组参数的程序的文件,然后使用它们的参数运行这些程序。

每个程序(行)一次执行一个,然后父进程等待每个子进程退出并检查它的退出状态(我只对它是否为 0 感兴趣)。

要解析的文本示例:

prog1 -a arg1 -m arg2 -c arg3 prog2 arg1 arg2 arg3 arg4 ....

我认为最好将所有内容存储在字符串 vector 中,例如:

vector <std::string> p_vector;
while (getline(file, line))
    p_vector.push_back(line);

然后,对于从 0 到 p_vector.size() 的每个元素 i,我需要做一些类似于我在网上找到的示例:

if(fork() = 0) //? shouldn't here be == ?
{
    execv(fullpath,argv);//does full path mean my p_vector[i]? or the child process and then argv is a list of space delimited arguments?
    exit(1);
}
else
{
    int *status;
    wait(status);
    if(*status == 0)
    printf("%s exited correctly", fullpath);//fullpath, right?
    else
    //other printf error
}

或者,我应该更好地使用它

string command = p_vector[i]; // eg: ls -l -a -l folder_one , put more arguments because I do not know the exact number of them for each parsed line

int exitCode = system(command.c_str());

如果有人也知道如何使用脚本执行此操作,那也很受欢迎,尽管我的问题范围是 C++!

我本可以使用 Qt 的 QProcess,因为我知道如何使用它,但这可能会引发一些我现在意识到的法律问题(共享代码没有问题,但我工作的公司可能不会允许)

感谢并期待从您那里得到一些答案!

最佳答案

我同意伊格纳西奥的观点。但是如果你必须这样做,那么我更希望你使用 System/popen 命令。

但请确保您没有运行任何会给您带来麻烦的命令……例如“rm -rf *”。

如果您要从不可信任的文件中读取,则很可能会发生这种情况。

无需将其复制到新字符串,您可以执行“system(p_vector[i].c_str());”

关于C++ - Linux/shell 脚本运行子进程并获取它们的返回状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6888585/

相关文章:

linux - 删除以非数字数据开头的行并在 linux 中的特定文本格式之前插入文本

linux - grep 中 "^-"的用法

c++ - 串口编程中的PNP(Plug and Play)事件处理

c++ - 打印字符串的所有子串时出错

c++ - 实时检测图像是否不同

运行时的 C++ 去虚拟化?

php - 我怎样才能在 linux 中进行非对称 cron 作业?

linux - 寻找一个非常简单的 Bash 脚本来自动按键

bash - Atom Snippets 不适用于 Shell 脚本

c++ - 为什么在具有多个接口(interface)() 的对象中实现 QueryInterface() 时我需要显式向上转换