Advertisement
xerpi

b7ping

Dec 1st, 2014
310
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.73 KB | None | 0 0
  1. #include <stdlib.h>
  2. #include <stdio.h>
  3. #include <string.h>
  4. #include <unistd.h>
  5.  
  6. #define xstr(s) str(s)
  7. #define str(s) #s
  8. #define NUM_COPS 5
  9. #define DELAY    0.5
  10.  
  11. int do_ping(const char *url, double *time)
  12. {
  13.     double acum = 0.0, cur_time = 0.0;
  14.     int i, cops_fet = 0;
  15.     int fd[2];
  16.     pipe(fd);
  17.    
  18.     int pid = fork();
  19.     if (pid == 0) {
  20.         close(fd[0]);
  21.         close(1);
  22.         dup2(fd[1], 1);
  23.         close(fd[1]);
  24.         execlp("ping", "ping", "-i", xstr(DELAY), "-c", xstr(NUM_COPS), url, NULL);
  25.         exit(0);
  26.     } else if (pid > 0) {
  27.         close(fd[1]);
  28.         char buff[512];
  29.         int n;
  30.         while ((n = read(fd[0], buff, sizeof(buff)-1)) > 0) {
  31.             buff[n] = '\0';
  32.             char *p = strstr(buff, "time=");
  33.             if (p) {
  34.                 p += strlen("time=");
  35.                 cur_time = 0.0;
  36.                 sscanf(p, "%lf", &cur_time);
  37.                 printf("%s: %lf\n", url, cur_time);
  38.                 if (cur_time > 0.0) {
  39.                     cops_fet++;
  40.                     acum += cur_time;
  41.                 }
  42.             }
  43.         }
  44.         close(fd[0]);
  45.         waitpid(-1, NULL, 0);
  46.         *time = acum/cops_fet;
  47.     } else {
  48.         printf("fork() error\n");
  49.         return 0;
  50.     }
  51.     return 1;
  52. }
  53.  
  54. int main(int argc, char *argv[])
  55. {
  56.     if (argc < 3) {
  57.         printf("Usage:\n\t b7ping serverlist outfile\n");
  58.         return -1;
  59.     }
  60.  
  61.     FILE *fp_in, *fp_out;
  62.     char *line = NULL;
  63.     size_t len = 0;
  64.     ssize_t read;
  65.  
  66.     fp_in = fopen(argv[1], "r");
  67.     if (fp_in == NULL) {
  68.         printf("Error opening %s\n", argv[1]);
  69.         return-1;
  70.     }
  71.    
  72.     fp_out = fopen(argv[2], "w");
  73.     if (fp_in == NULL) {
  74.         printf("Error opening %s\n", argv[2]);
  75.         return-1;
  76.     }
  77.    
  78.     double time;
  79.    
  80.     while ((read = getline(&line, &len, fp_in)) != -1) {
  81.         line[strlen(line)-1] = '\0';
  82.         do_ping(line, &time);
  83.         fprintf(fp_out, "%s %f\n", line, time);
  84.         usleep(100*1000);
  85.     }
  86.    
  87.     fclose(fp_in);
  88.     fclose(fp_out);
  89.     if (line) free(line);
  90.     return 0;
  91. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement