如何在C中执行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));

请帮忙.我需要这个 .

解决方法:

除了实际问题之外,我还会使用

sudo netstat -tlpn

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

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

sudo netstat -tlpn | grep :7761

找到哪个端口:7761正在收听?

你可以使用popen.

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

直接来自Standards Documentation的样本:

The following example demonstrates the use of popen() and pclose() to execute the command ls * in order to obtain a list of files in the current directory:

#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() */
    ...
}

相关文章

用的openwrt路由器,家里宽带申请了动态公网ip,为了方便把2...
#!/bin/bashcommand1&command2&wait从Shell脚本并行...
1.先查出MAMP下面集成的PHP版本cd/Applications/MAMP/bin/ph...
1、先输入locale-a,查看一下现在已安装的语言2、若不存在如...
BashPerlTclsyntaxdiff1.进制数表示Languagebinaryoctalhexa...
正常安装了k8s后,使用kubect工具后接的命令不能直接tab补全...