What is the difference between system
and exec
family commands? Especially I want to know which one of them creates child process to work?
The exec system call is used to execute a file which is residing in an active process. When exec is called the previous executable file is replaced and new file is executed.
The Linux exec command executes a Shell command without creating a new process. Instead, it replaces the currently open Shell operation. Depending on the command usage, exec has different behaviors and use cases.
The system() library function uses fork(2) to create a child process that executes the shell command specified in command using execl(3) as follows: execl("/bin/sh", "sh", "-c", command, (char *) NULL); system() returns after the command has been completed.
The exec() system call is used to replace the current process image with the new process image. It loads the program into the current space, and runs it from the entry point. So the main difference between fork() and exec() is that fork starts new process which is a copy of the main process.
system()
calls out to sh
to handle your command line, so you can get wildcard expansion, etc. exec()
and its friends replace the current process image with a new process image.
With system()
, your program continues running and you get back some status about the external command you called. With exec()
, your process is obliterated.
In general, I guess you could think of system()
as a higher-level interface. You could duplicate its functionality yourself using some combination fork()
, exec()
, and wait()
.
To answer your final question, system()
causes a child process to be created, and the exec()
family do not. You would need to use fork()
for that.
The exec function replace the currently running process image when successful, no child is created (unless you do that yourself previously with fork()
). The system() function does fork a child process and returns when the command supplied is finished executing or an error occurs.
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