[英]An alternative way to get console output of system() function
在控制台中執行以下代碼時:
int ret = system("iptables -t filter -L");
ret
將獲得值1
並且控制台中將顯示規則列表。 問題是我還想獲取程序內部的規則列表。 我正在使用以下解決方案進行此操作:
int ret = system("iptables -t filter -L >> filter-table.txt");
/* read filter-table.txt file to get the list */
還有什么要獲取列表的嗎?
如@Charles Duffy和@Kevin所述, system()
不是您想要的功能。 popen()
更合適。 以下應該工作。 請注意,如果使用gcc
並使用-std=c99
標志進行編譯,則需要在#include <stdio.h>
之前添加#define _POSIX_C_SOURCE 2
#include <stdio.h>
#include <error.h>
#define PATH_MAX 1024
int main(void)
{
FILE *fp;
int status;
char path[PATH_MAX];
fp = popen("iptables -t filter -L", "r");
if (fp == NULL)
{
perror("popen");
return -1;
}
while (fgets(path, PATH_MAX, fp) != NULL)
{
printf("%s", path);
/* do something you want with the return data */
}
status = pclose(fp);
if (status == -1)
{
perror("pclose");
}
return 0;
}
您應該在發行版上安裝iptables-devel,並在代碼中直接包含de library以構建更簡潔的內容。 代替使用輸出。
您會在此鏈接上找到提示: http : //www.bani.com.br/2012/05/programmatically-managing-iptables-rules-in-c-iptc/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.