gpt4 book ai didi

c++ - 使用 exec/fork 运行外部进程

转载 作者:行者123 更新时间:2023-11-28 08:16:12 26 4
gpt4 key购买 nike

我正在使用 C++ 并尝试在外部进程中运行 shell 命令。这是我到目前为止的代码:

pid_t pid;
pid = fork();
if(pid == 0){
execv(args[0],args);
} else {
wait();
}

我的第一个问题是我需要从传递给 exec 的 shell 命令中获取输出,但我不知道如何获取它。运行上面的代码后,主程序也会 self 复制,我不确定为什么。

最佳答案

args[0] 大概是正在运行的程序的名称,因此它会 fork 然后执行自己。

为了收集输出,您需要安排明确传递它。为此经常使用 Unix pipe() 调用。

关于c++ - 使用 exec/fork 运行外部进程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7701479/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com