views:

86

answers:

3

I need to execute a unix command with different args in a loop. Now I wonder if I should use execvp(), passing in the cmd and the args, or use system, building a string consisting of cmd + args?

+6  A: 

The exec family of functions will replace the current process with a new one, whilst system will fork off the new process, and then wait for it to finish. Which one to use depends on what you want.

Since you're doing this in a loop, I guess you don't want to replace the original process. Therefore, I suggest you try to go with system.

Hans W
system also subjects the line to command line parsing, which might open up holes for injection attacks.
roe
I looked for some tutorials on this on the web and most examples fork()ed a new process and than replaced the fork with execvp(). After that, the parent process waited for the child process to finish. Is this basically what system() does?
Helper Method
Yes, that is basically what `system()` does. Calling `system()` also runs the default shell and passes your program as the argument, which will create a bit more overhead.
jschmier
+3  A: 

I'd use execvp only if I can't achieve what I want with system. Note that to get the equivalent of system, you need execvp, fork and some signal handling as well.

AProgrammer
+5  A: 

Well, the other answers are mostly correct.

System, while not only forks and then execs, it doesn't exec your process, it runs the default shell, passing your program as an argument.

So, unless you really want a shell (for parameter parsing and the like) it is much more efficient to do something like:

int i = fork();
if ( i != 0 ) {
    exec*(...); // whichever flavor fits the bill
} else {
    wait(); // or something more sophisticated
}
Jeff Walker