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.

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;
}

> 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:");

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

Can anyone please explain to me the detials of what the fork command does??

Like wat is the Pid of the parent for a child created using this command.. again also it is said that it creates a replica of the currently running process what does this exactly mean??

Do reply Thank You...

Can anyone please explain to me the detials of what the fork command does??

Like wat is the Pid of the parent for a child created using this command.. again also it is said that it creates a replica of the currently running process what does this exactly mean??

Do reply Thank You...

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

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.