Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdlib.h>
- #include <stdio.h>
- #include <string.h>
- #include <unistd.h>
- #define xstr(s) str(s)
- #define str(s) #s
- #define NUM_COPS 5
- #define DELAY 0.5
- int do_ping(const char *url, double *time)
- {
- double acum = 0.0, cur_time = 0.0;
- int i, cops_fet = 0;
- int fd[2];
- pipe(fd);
- int pid = fork();
- if (pid == 0) {
- close(fd[0]);
- close(1);
- dup2(fd[1], 1);
- close(fd[1]);
- execlp("ping", "ping", "-i", xstr(DELAY), "-c", xstr(NUM_COPS), url, NULL);
- exit(0);
- } else if (pid > 0) {
- close(fd[1]);
- char buff[512];
- int n;
- while ((n = read(fd[0], buff, sizeof(buff)-1)) > 0) {
- buff[n] = '\0';
- char *p = strstr(buff, "time=");
- if (p) {
- p += strlen("time=");
- cur_time = 0.0;
- sscanf(p, "%lf", &cur_time);
- printf("%s: %lf\n", url, cur_time);
- if (cur_time > 0.0) {
- cops_fet++;
- acum += cur_time;
- }
- }
- }
- close(fd[0]);
- waitpid(-1, NULL, 0);
- *time = acum/cops_fet;
- } else {
- printf("fork() error\n");
- return 0;
- }
- return 1;
- }
- int main(int argc, char *argv[])
- {
- if (argc < 3) {
- printf("Usage:\n\t b7ping serverlist outfile\n");
- return -1;
- }
- FILE *fp_in, *fp_out;
- char *line = NULL;
- size_t len = 0;
- ssize_t read;
- fp_in = fopen(argv[1], "r");
- if (fp_in == NULL) {
- printf("Error opening %s\n", argv[1]);
- return-1;
- }
- fp_out = fopen(argv[2], "w");
- if (fp_in == NULL) {
- printf("Error opening %s\n", argv[2]);
- return-1;
- }
- double time;
- while ((read = getline(&line, &len, fp_in)) != -1) {
- line[strlen(line)-1] = '\0';
- do_ping(line, &time);
- fprintf(fp_out, "%s %f\n", line, time);
- usleep(100*1000);
- }
- fclose(fp_in);
- fclose(fp_out);
- if (line) free(line);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement