从执行的应用程序获取标准输出
有谁知道如何从 execvp 捕获输出(我认为是标准输出),而不是系统在终端中打印它(在 Linux 上的 c 中)?
Does anyone know how to catch the output (I think its stdout) from execvp
instead of the system printing it (in c on linux) in the terminal?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
execvp
替换内存中当前正在运行的进程。没有“捕获”输出。我怀疑您正在尝试从现有进程运行外部进程,并解析其输出。为此,您需要使用
popen()
执行fork()
然后执行exec()
,返回一个FILE *< /code> 来读取(这将是您刚刚运行的进程的
stdout
)。execvp
replaces the current running process in memory. There's no "catching" the output.I suspect you're trying to run an external process from an existing process, and parse its output. For that you need to use
popen()
which does afork()
then anexec()
, returning aFILE *
to read (which will be thestdout
of the process you just ran).我不信任
popen/pclose
,因为我工作过太多系统,其中SIGCHLD
的处理方式略有不同。而且我不信任popen
使用的sh
-shell 解析,因为我很少使用它。O'Reilly 22 年的短书 在 UNIX 上使用 C Dave Curry 的 System 仍然是此类内容的非常很好的参考。
无论如何,这里有一些代码。它有点长,因为它将示例字符串
"/bin/ls /etc"
解析为数组{"/bin/ls", "/etc", 0}.但我发现使用字符串格式在 98% 的时间里更容易并且更短,尽管这个例子掩盖了这一点。
此代码生成
/etc.
列表。您需要更改一些内容,例如NUMBER()
,它与XtNumber()
相同>。您需要确定它是否与您对SIGCHLD
的处理相匹配。这里的子例程是:
这将 ascii 字符串转换为
argv
列表,这对您来说可能没用:这将参数字符串转换为标记,更重要的是,将
fd
到fp
,因为 OP 请求了stdout
:I distrust
popen/pclose
, as I've worked on too many systems whereSIGCHLD
was handled slightly differently. And I distrust thesh
-shell parsing used bypopen
, since I rarely use it.The short 22-year-old O'Reilly book Using C on the UNIX System, by Dave Curry is still a very good reference for this sort of stuff.
Anyway, here is some code. It is a bit lengthy, as it parses the sample string
"/bin/ls /etc"
into the array{"/bin/ls", "/etc", 0}
. But I find using the string format easier and shorter 98% of the time, although this example belies that.This code generates a listing of
/etc.
You'll need to change some stuff like e.g.NUMBER()
which is the same asXtNumber()
. And you'll need to decide whether it matches your handling ofSIGCHLD
.The subroutines here are:
This converts an ascii string to an
argv
list, which is probably useless to you:This converts the argument string to tokens and, more importantly, the
fd
to anfp
, since the OP requestedstdout
:请参阅
popen
的文档,我认为这正是你的需要。See the documentation of
popen
, I think it's exactly what you need.正如其他人所说,
popen
就是您想要使用的。像这样的东西...As others have said,
popen
is what you want to use. Something like this...我找到了这个答案,它为
popen
提供了execvp
风格的界面。https://codereview.stackexchange.com/questions/31063/popen-with-array- of-参数
I found this answer, which gives
popen
aexecvp
style interface.https://codereview.stackexchange.com/questions/31063/popen-with-array-of-arguments