Which code is faster

Hello All,

This is my first post in the forum.

I have following two sample codes written in Linux. Both of them print the network interface names of the linux system. My question is which code is faster and reliable and why?

Here is the code 1


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

using namespace std;

int main ()
{
	char *tok;
	char command1[255] = "echo $(/sbin/ip -o link show up | awk -F : '{ print $2 }')";
	FILE *fp;
	int status;
	char path[128]= {0};
	
	fp = popen(command1, "r");
	if (fp != NULL)
	{
		while (fgets(path, 128, fp) != NULL)
		{
			status = pclose(fp);
			tok = strtok(path," ");

			while(tok != NULL)
			{
				printf("%s\n",tok);				
		    	        tok = strtok(NULL, " ");
    		        }
		}
	}
 	return 0;
}



Here is the code 2


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#include <stdio.h>
#include <unistd.h>
#include <netinet/in.h>
#include <sys/ioctl.h>
#include <net/if.h>
#include <string>
#include <stdlib.h>
#include <iostream>
#include<string.h>

using namespace std;

int main()
{		
	int sock;
    struct ifreq ifreq;

    if((sock = socket(AF_INET, SOCK_STREAM, 0)) != -1)
    {
        for(int x = 1; x < 10; x++)
        {
           ifreq.ifr_ifindex = x;

           if(ioctl(sock, SIOCGIFNAME, &ifreq) !=  -1 )
           {
                printf("%s\n", ifreq.ifr_name);
           }
         }
     }
		
	close(sock);
}


Please let me know your comments.


Thanks,
Nandakumar
/sbin/ip -o link show up | awk -F : '{ print $2 }' without all the C code is definitely the way to go.

Otherwise, choose #2. Calling external commands from C programs is never the way to go. Paths where executables are kept change, you have no clue which version of awk is being called, the fork may fail due to resource issues. There is very little that can go wrong with the last one using the Unix C API..
#2 is orders of magnitude faster and infinitely more reliable since it is not dependent upon external programs. (and thus
infinitely more secure also).

closed account (S6k9GNh0)
PanGalactic, why would you recommend using an external program from native code?

EDIT: Ah, I misread.
Last edited on
@computerquip: I didn't. I said either use the shell portion directly ("without all the C code") or use #2.
So it #2 which is faster and reliable !

Thank you PanGalactic, jsmith, computerquip for your valuable comments
Topic archived. No new replies allowed.