如何使用C程序进入网络命名空间并读取文件内容

How to enter in to network namespace and read the file content using C program

在我的 Linux 机器上,我配置了网络命名空间。使用 shell 脚本或命令行或系统命令,我能够获取网络命名空间中存在的文件内容。

ip netns exec test_namespace cat /var/test_namespace/route.conf

输出:

cardIP=10.12.13.1

在 C 程序中,我可以使用 system("ip netns exec test_namespace cat /var/test_namespace/route.conf") 命令来获取输出。但是我不想使用这个选项。

正在寻找替代方法,我不确定系统调用setns,如何使用它。有什么想法吗?

如果您对 system 过敏,您可以使用 popen 将脚本输出读取为文件:


例子

/* the command to execute */
FILE *f = popen("ls", "r");

/* Here, we should test that f is not NULL */
printf("result of `ls`:\n");

/* read process result */
char buffer[256];
while (fgets(buffer, sizeof buffer, f)  
{
    puts(buffer);
}

/* and close the process */
pclose(f);