如何标记命令的输出并存储在变量的链接列表中?

时间:2018-07-09 21:49:42

标签: c

我写了一个python脚本,该脚本提供了如下所述的输出。

interface   mac_address         ip_address        rx_bytes         rx_packets       start_time    end_time    
eth3        01:00:02:20:cd:d3   122.168.12.12       648              8                1531167452.33  1531167452.36
eth2        03:00:02:b5:ef:7e   122.168.3.14       75303498         843297           1531167452.33  1531167452.36
eth1        04:00:02:25:6c:b1   122.168.2.15       76756884         846595           1531167452.33  1531167452.36

我正在使用execlp系统调用从C程序调用此python脚本,并希望将每个标记化的值(即接口名称,mac等)存储到结构链接列表中。我可以从C程序调用python脚本,但是我不确定如何解析此输出并将其存储在链接列表结构中。

#include <stdio.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <string.h>
#include<stdlib.h>
int main(void) 
{
  pid_t child;
  pid_t c; /* Pid of child to be returned by wait. */
  int cstatus;
  int stdout_fds[2];
  char foo[4096 + 1];
  int rc;


  int nbytes = 0;

  memset(foo, 0, 4096);


  rc = pipe(stdout_fds);
  if (rc != 0) {
    printf("pipe() failed \n");
    return;
  }


  if ((child = fork()) == 0) {

     /* Child process. To begin with, it prints its pid. */
     printf("Child process executes the commandi");
     close(stdout_fds[0]);
     dup2(stdout_fds[1], STDOUT_FILENO);

     /* Child will now execute */
     execlp("/usr/bin/python", "python", "counters.py", NULL);

     fprintf(stderr, "Child process could not do execlp.\n");

     close(stdout_fds[1]);

     exit(1);
  }
  else 
  { 
     /* Parent process. */
     if (child == (pid_t)(-1)) {
        fprintf(stderr, "Fork failed.\n"); exit(1);
     }
     else 
     {
        close(stdout_fds[1]);

        while(0 != (nbytes = read(stdout_fds[0], foo, sizeof(foo)))) {
          printf("%s", foo);
          memset(foo, 0, 4096);
        }

       c = waitpid(child, &cstatus, 0); /* Wait for child to complete. */
       printf("Parent: Child %ld exited with status = %d\n",(long) c, cstatus);
     }
  }
  return 0;
} /* End of main. */

[root@ ~]# ./test.exe 
 interface   mac_address         ip_address        rx_bytes         rx_packets       start_time    end_time    
eth3        01:00:02:20:cd:d3   122.168.12.12       648              8                1531167452.33  1531167452.36
eth2        03:00:02:b5:ef:7e   122.168.3.14       75303498         843297           1531167452.33  1531167452.36
eth1        04:00:02:25:6c:b1   122.168.2.15       76756884         846595           1531167452.33  1531167452.36

从上面的输出中,想读取每一行并标记每个值并存储在结构中并在链接列表中表示。任何人都可以提出一些最佳的优化技术来做到这一点。

结构示例:

struct entry
{ 
   char interface_name[24];
   char mac[32];
   char ip_address[40];
   char rx_bytes[256];
   char rx_packets[256]; 
   char start_time[256];
   char end_time[256];
}p[3];

p[0] -> p[1] -> p[3]

0 个答案:

没有答案