Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between using fork/execvp and system call

Tags:

c++

c

linux

unix

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.

like image 228
foo Avatar asked Nov 20 '08 09:11

foo


People also ask

What is the difference between fork () and exec () system calls?

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.

Why do we need separate fork () and exec () system calls instead of one combined system call that does both?

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.

How are fork () and exec () system calls different from normal system function calls in terms of their call return behavior?

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.


5 Answers

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).

like image 153
flolo Avatar answered Sep 23 '22 03:09

flolo


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.

like image 25
unwind Avatar answered Sep 24 '22 03:09

unwind


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()

like image 30
qrdl Avatar answered Sep 22 '22 03:09

qrdl


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.

like image 44
finnw Avatar answered Sep 22 '22 03:09

finnw


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

like image 34
n-alexander Avatar answered Sep 24 '22 03:09

n-alexander