the difference of using fork() and exec() with system()
Hello there. Is there someone kind enough to please explain to me the difference of using fork() and exec() with system() in invoking a process. I just want to know their difference according to well experienced with processes here. And what is the most efficient in invoking a process between the two. Thanks.
jaepi
Practically a Master Poster
647 posts since Jul 2006
Reputation Points: 32
Solved Threads: 4
In addition, I have here a test program. I used fork and exec to execute the command in Linux "switch user" or the "su" command. I was surprised to see two outputs. It executed two "su" commands. Does this mean that forking a child will create a copy of a process when exec is used??
Here's my test program.
#include <iostream>
#include <unistd.h>
using namespace std;
int main(){
const char* command = "su";
pid_t child_p;
child_p = fork();
execvp(command, NULL);
return 0;
}
jaepi
Practically a Master Poster
647 posts since Jul 2006
Reputation Points: 32
Solved Threads: 4
> It executed two "su" commands.
Yes it will (as written). After fork() returns, then you have two processes doing exactly the same thing (for a short while at least usually).
Mostly, it works like this
pid = fork();
if ( pid == 0 ) {
// in the child, do exec
execvp(command, NULL);
} else
if ( pid != (pid_t)-1 ) {
// in the parent, now perhaps do wait(pid)
} else {
// still in parent, but there is no child
}
> the difference of using fork() and exec() with system() in invoking a process
Convenience vs. control (and safety).
system() is a very quick (and unsafe) way of running another process. fork()/execl() give you a lot more control over what is going on.
Why is system unsafe?
It relies on the user not being malicious in manipulating the PATH environment, or which command shell gets invoked to parse the command line. Either of these could easily turn your system("pause"); into system("format c:");
Salem
Posting Sage
11,531 posts since Dec 2005
Reputation Points: 5,862
Solved Threads: 953
As what I have read, after forking, the main program was split into 2, thus creating the child process as the copy of the parent, that's why "su" performed twice. <- Am I correct with that? Thank you very much for that detailed explanation. :)
jaepi
Practically a Master Poster
647 posts since Jul 2006
Reputation Points: 32
Solved Threads: 4
fork
exec
Pid = a Process ID. It's just a number unique to 1 process. PPID is it's parent.
Next time if you have a question please read the rules . This thread was a year old, so ask your questions in a new one please.
Niek
Nick Evan
Not a Llama
10,112 posts since Oct 2006
Reputation Points: 4,142
Solved Threads: 403