开发者

When to use system() and when to use execv*()?

开发者 https://www.devze.com 2022-12-20 18:44 出处:网络
I need to execute a unix command with different args in a loop. Now I wonder if I should us开发者_Go百科e execvp(), passing in the cmd and the args, or use system, building a string consisting of cmd

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


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
}


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消