I have this c++ program that is doing a simple ping on a specified ip address. I am not into networking so i’m just using the system() command in c++ to execute the ping from a shell and store the results in a file, that’s easy.
The problem is that i want some dots to be printed on the screen while the system() command is being executed. i tried with:
while(system(cmd))
{
//execute the task here
}
but no success. I think that i should create threads or something.
Can you help me ? What exactly i am supposed to do in order to get this done as i want to ?
You need to create a forked process using
fork, like this, and usingpopento read the input from the output of the commandping google.comand process it accordingly. There is an interesting guide by Beej on understanding the IPC mechanisms which is included in the code sample below…#include <stdio.h> #include <stdlib.h> #include <errno.h> #include <unistd.h> #include <sys/types.h> #include <sys/wait.h> int main(void) { pid_t pid; int rv; FILE *ping; char buf[2000]; switch(pid = fork()) { case -1: perror("fork"); /* something went wrong */ exit(1); /* parent exits */ case 0: // We're the child ping = popen("ping google.com", "r"); if (ping != NULL){ fgets(buf, sizeof(buf), ping); pclose(ping); rv = 0; }else{ perror("popen failed"); rv = -1; } exit(rv); default: // We're the parent... wait(&rv); } // Now process the buffer return 0; }Hope this helps,
Best regards,
Tom.