微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何在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() */
    ...
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐