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.
The fork() returns the PID of the child process. If the value is non-zero, then it is parent process's id, and if this is 0, then this is child process's id. The exec() system call is used to replace the current process image with the new process image.
The main reason is likely that the separation of the fork() and exec() steps allows arbitrary setup of the child environment to be done using other system calls.
A call to fork() returns once or twice - the latter on success where it returns once in the parent and once in the child, the former on failure where it simply returns once in the parent. A call to exec() will return on failure but, if successful, the current process is simply overwritten with a new program.
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).
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.
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()
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.
there's also popen(), which is like system(), but allows to read child's output and provide input
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With