Skip to content
Advertisement

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

In my Linux machine, i have configured the network namespace. With shell script or command line or system command I was able to fetch the file content present in the network namespace.

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

Output:

cardIP=10.12.13.1

In a C program, I can use system("ip netns exec test_namespace cat /var/test_namespace/route.conf") command to get the output. But I prefer not to use this option.

Looking for an alternative method, I am not sure about the system call setns, how to use it. Any ideas?

Advertisement

Answer

If you’re alergic to system, you can use popen to read the script output as a file:


Example

/* 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);
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement