tags:

views:

175

answers:

4

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 ?

+7  A: 

The problem with system is that it suspends execution until completion. On unix systems you will need to use a sequence of fork, execv, dup2 and pipe. This will allow you to do something more useful. See http://docs.linux.cz/programming/c/unix_examples/execill.html for an example.

doron
Redacted comment: You can save some trouble on the `fork`, `exec`, `pipe` combo by using `popen` if you are satisfied with uni-directional communication.
dmckee
+1  A: 

If you are on a unix system, you can start a command with an & to indicate that it runs in the background like this: myscript &

This will start a new process separate from the current program. You need to pick up the process number (hopefully from system, my c posix api knowledge is rusty) and then check up on it probably with a call to something like wait or waitpid with non-blocking turned on.

This is complicated for a beginner -- I'll let someone else post details if still interested.

Paul
+2  A: 

Edit On consideration, I believe that popen is the way to go with or without output from cmd.


Older

You are probably looking for something in the wait (2) family of commands plus a fork and exec.

From the manual page

The wait() function suspends execution of its calling process until stat_loc information is available for a terminated child process, or a signal is received. On return from a successful wait() call, the stat_loc area contains termination information about the process that exited as defined below.

Or if cmd returns some progress information you want popen (3) which is discussed in a number of existing SO questions; for instance How can I run an external program from C and parse its output?.

dmckee
To him that may mean he actually doesn't want to call wait(), because it will block until the child process finishes, which he wants to avoid. I seem to remember a non-blocking option or parameter, though. Good answer, anyway.
Paul
+5  A: 
tommieb75