如何在C中执行bash命令并检索输出?

时间:2011-11-13 14:09:24

标签: c linux bash

我正在尝试从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));

请帮忙。我需要这个。

2 个答案:

答案 0 :(得分:6)

编辑除了实际问题,我会使用

sudo netstat -tlpn

(显示正在侦听TCP端口的进程,而不是解析端口/地址)

也许将它与一些grep结合起来:

sudo netstat -tlpn | grep :7761

找到正在收听端口:7761的位置?


您可以使用popen

使用popen,您可以获得异步接收进程输出的好处(如果答案位于输出的第一行,您将能够停止处理,而无需等待子进程完成;只需pclose并且子进程将以SIGPIPE

消亡

直接来自Standards Documentation的示例:

  

以下示例演示如何使用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() */
    ...
}

答案 1 :(得分:1)

system(command)返回命令的返回码,而不是其输出。 如果要读取命令的输出,则应使用popen 这会将文件描述符返回给输出,您可以像普通文件一样读取它。