tags:

views:

1534

answers:

5

Hi

What is the difference between using system() to execute a binary and using the combination of fork/execvp.

Is there any security/portablility/performance difference.

+4  A: 

Yes, system() runs the command through a shell, while exec() runs the command directly. Of course, introducing a shell opens up for bugs and exploits.

Edit: of course, the man page provides more detail.

unwind
"introducing a shell opens up for bugs and exploits" - Only if you allow a person to type the commands. If your application generates the text of the shell command, there's no possibility of an exploit.
S.Lott
One possibility is if user changes some shell variables before your code is executed. There is a possibility of exploit, but not sure how generic it is.
foo
A: 

system() works on Windows but fork() doesn't.

Unless you use a compatibility layer such as Cygwin, but even then a fork can be very expensive.

finnw
the question is tagged linux/unix, so a windows answer isn't that helpful...
Nathan Fellman
@Nathan, The question mentions portability differences, which this is.
finnw
I have a question on the issue of expense, How is fork more expensive than system. System too forks a process, instead it forks two processes.
foo
+3  A: 

System also uses a fork/exec... combination. If you do fork/exec yourself you can execute parallel to your running process, while system is blocking (includes the wait). Also system executes the command not direct, but via a shell (which makes problems with setuid bit) and system blocks/ignores certain signals (SIGINT, SIGCHILD, SIGQUIT).

flolo
+1  A: 

there's also popen(), which is like system(), but allows to read child's output and provide input

n-alexander
+1  A: 

system() will fork()/exec() the shell, and then shell will fork()/exec() the program you want to launch.

So system() is twice as heavy as fork()/exec()

qrdl