我正在尝试从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()
andpclose()
to execute the commandls *
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() */
...
}