如何在 C 中执行 bash 命令并检索输出?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8112108/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to execute a bash command in C and retrieve output?
提问by Badea Sorin
I'm trying to execute a bash command from c and retrieve and show the result. I've tried with system but it doesn't work. My code looks like:
我正在尝试从 c 执行 bash 命令并检索并显示结果。我试过系统,但它不起作用。我的代码看起来像:
char command[200];
sprintf(command,"lsof -iTCP:%d | cut -d\"\" -f1 | tail -1",port);
printf("Port %d is open\n and is listened by %s",port,system(command));
Please help. I need this .
请帮忙。我需要这个 。
回答by sehe
Editaside from the actual question, I'd be using
编辑从实际的问题不谈,我会使用
sudo netstat -tlpn
(shows the processes that are listening on TCP ports, not resolving the ports/addresses)
(显示正在侦听 TCP 端口的进程,而不是解析端口/地址)
Perhaps combine it with a bit of grep:
也许将它与一些 grep 结合起来:
sudo netstat -tlpn | grep :7761
to find where port :7761 is being listened?
找到端口 :7761 被监听的位置?
You can use popen.
您可以使用popen.
With popen you get the benefit that you receive the process output asynchronously (you will be able to stop processing if the answer is on the first line of output without having to wait for the subprocess to complete; simply pcloseand the subprocess will die with SIGPIPE)
使用 popen,您可以获得异步接收流程输出的好处(如果答案在输出的第一行,您将能够停止处理而无需等待子流程完成;简单地pclose,子流程将随着 结束SIGPIPE)
A sample straight from the Standards Documentation:
直接来自标准文档的示例:
The following example demonstrates the use of
popen()andpclose()to execute the commandls *in order to obtain a list of files in the current directory:
以下示例演示了如何使用
popen()和pclose()执行命令ls *以获取当前目录中的文件列表:
#include <stdio.h>
...
FILE *fp;
int status;
char path[PATH_MAX];
fp = popen("ls *", "r");
if (fp == NULL)
/* Handle error */;
while (fgets(path, PATH_MAX, fp) != NULL)
printf("%s", path);
status = pclose(fp);
if (status == -1) {
/* Error reported by pclose() */
...
} else {
/* Use macros described under wait() to inspect `status' in order
to determine success/failure of command executed by popen() */
...
}
回答by Jarek
system(command) returns the return code of the command, not its output. If you want to read the output of a command, you should use popenThis returns a file descriptor to the output, which you can read from just like a normal file.
system(command) 返回命令的返回码,而不是它的输出。如果你想读取命令的输出,你应该使用popen这会返回一个文件描述符到输出,你可以像普通文件一样读取它。

